0

I am having issues with displaying from a float SQL data type onto my textbox. So far I can get strings to display just fine as well as int data types. When it comes to floats or even decimals it wants to throw a fit and I'm not entirely sure why. Here is the error I'm getting:

Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)

How do I force ships.Height = (float)shipReader["HeightTest"]; to be a float and not an int because if I just left it as with an int it still won't display it without throwing an error. Which when you run it it will pop an error message,"Specified cast is not valid."

SqlDataReader shipReader = 
                    selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if(shipReader.Read())
{
    Ships ships = new Ships();
    ships.Role = shipReader["Role"].ToString();
    ships.Description = shipReader["Description"].ToString();
    ships.NullCargoMass = (int)shipReader["NullCargoMass"];
    ships.Height = (float)shipReader["HeightTest"];
    return ships;
}
2
  • 1
    What is the exact database type for HeightTest ?, and also what is the type of Ships.Height ? Commented Feb 19, 2014 at 1:35
  • When you mentioned Ships.Height I wasn't sure actually which data type it was being assigned as till I look at my other classes. Now I figured out my problem thank you. Commented Feb 19, 2014 at 2:22

2 Answers 2

2
ships.Height = Convert.ToSingle(shipReader["HeightTest"]);
Sign up to request clarification or add additional context in comments.

3 Comments

Still getting the: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) error message while using this code.
What is the datatype of ships.Height ?
Actually it does work I wasn't paying attention to another class that I had which was an int. I switched it and now it's working and this code works. Thanks
1

Use the helper method GetFloat available via the SqlDataReader object.

shipReader.GetFloat(shipReader.GetOrdinal("HeightTest"))

1 Comment

Just a tip outside of the scope of this question, but it's best practice to place your SqlDataReader object inside a using statement. Not only does it ensure that the unmanaged resources consumed by the object are freed when they are no longer needed, but it also doubles as a check to make sure that the SqlDataReader is closed when it is done reading. Remember that Dispose() calls Close() for SqlDataReader.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.