简体   繁体   中英

double.Parse not working on DataGridView Cell Value

I've got a DataGridView that I'd like to apply formatting changes to based on cell values. I'd like to do it using the original DataTable source but unfortunately building the source required removing and reorienting certain rows so the indexes are off. As such, I'm trying to do it using

 double.TryParse(DataGridView
                .Rows[index]
                .Cells["ColumnName"]
                .FormattedValue.ToString(), out dbl);

however, it never recognizes the value as a double. I've verified the output using MessageBox'es and that there are no leading or trailing spaces that might cause issue by adding "-" to both sides of the MessageBox string. I'm clueless as to why it will always regard the value as not a double even on values that are clearly parseable as doubles.

Edit : I'm not sure what changed over the weekend but I came in, fixed a different bug unrelated to this and now the bold is working using .Value rather than .FormattedValue as suggested by gh0st below.

double.TryParse() will parse the string in a culture dependant way. It is very likely that your current culture expects the decimal point to be some other symbol, like the comma or something.

For instance, on my machine, I can force it to fail the parsing by passing a different culture, like this:

double.TryParse("1.2", 
                NumberStyles.Float | NumberStyles.AllowThousands, 
                CultureInfo.GetCultureInfo("fr-FR"), 
                out dbl); // returns false

If this is what is happening to you, then either you find a way to change the current culture, or perhaps you can do the parsing this way instead to ensure consistent results:

double.TryParse("1.2", 
                NumberStyles.Float | NumberStyles.AllowThousands, 
                CultureInfo.InvariantCulture,
                out dbl); // returns true

(*) Note: the NumberStyles.Float | NumberStyles.AllowThousands NumberStyles.Float | NumberStyles.AllowThousands values can be adjusted as you like. I just set it to that in this example, because that is the default that the TryParse method uses when using the overload with less parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM