Casting datagridview cell as float

Josh M
 for (int i = 0; i < dgv.RowCount; i++)
 {
      pin.Size = (float)(dgv.Rows[i].Cells[2].Value);
 }

I have a class property of "Size", which is a float. A user can put a whole number or a decimal value. It's stored in the database (SQL) as a real. The value is supposed to stay as a float. When a user puts in a value in the 3rd column (Cells[2]), and clicks save....

Specified cast is not valid

However, I thought doing my code above should handle that for the cell. What are my other options for allowing a float value to a gridcell?

JNYRanger

There are a few reasons why this is not working. It could be because the value is null, it could be a string value, or it could be another object type that doesn't have an explicit cast to float. Since float is a primitive value, as opposed to an object it can never be null, hence the potential error. Strings also need to be parsed to become a number primitive, such as a float, as direct casting will throw an error

Your best bet is to do the following:

 for (int i = 0; i < dgv.RowCount; i++)
 {
      float value;
      if(Float.TryParse(dgv.Rows[i].Cells[2].Value, out value)
          pin.Size = value;
      else
          pin.Size = 0 //or whatever default value you'd like to use when not parsable to float,
 }

One other potential solution can be used if you know if you ALWAYS know that it's either a valid float or a null value.

pin.size = (float)(dvg.Rows[i].Cells[2].Value ?? 0)

The ?? operator is called the null coalescing operator and allows you to indicate an alternate value if something is null.

I would still make sure you run this through a debugger to make sure the value is of the type that you expect it to be. Although you may see the value as 0.0, the type may not necessarily be what you expect.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related