Get Numeric Value from DataGridViewCell?
Solution 1
I've actually just recently dealt with this problem and TryParse
I think is your best bet with respect to robustness, but don't forget to check if the value in the Cell is null
, if so TryParse
will fail and throw up an error.
double d = 0;
if(grid[col,row].Value != null)
double.TryParse(grid[col,row].Value.ToString(), out d);
I would also recommend avoiding a straight cast, unless you know absolutely what type you are converting and that there will, in fact, be a value there, it will probably at some point cause an error in your code.
Solution 2
With DataGridViewCell
you can just cast the .Value
to your known type; the following is a complete example that shows this happening (using double) from a DataTable
(like your example).
Additionally, Convert.To{blah}(...)
and Convert.ChangeType(...)
might be helpful.
using System.Data;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
DataTable table = new DataTable
{
Columns = {
{"Foo", typeof(double)},
{"Bar", typeof(string)}
},
Rows = {
{123.45, "abc"},
{678.90, "def"}
}
};
Form form = new Form();
DataGridView grid = new DataGridView {
Dock = DockStyle.Fill, DataSource = table};
form.Controls.Add(grid);
grid.CurrentCellChanged += delegate
{
form.Text = string.Format("{0}: {1}",
grid.CurrentCell.Value.GetType(),
grid.CurrentCell.Value);
if (grid.CurrentCell.Value is double)
{
double val = (double)grid.CurrentCell.Value;
form.Text += " is a double: " + val;
}
};
Application.Run(form);
}
}
Solution 3
DataGridViewCell
has ValueType
property. You can use to do directly cast the value to that type without first converting it to string:
if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null &&
MyGrid.SelectedRows[0].Cells[0].ValueType == Double)
return (Double)MyGrid.SelectedRows[0].Cells[0].Value;
Related videos on Youtube
Ali
Updated on May 01, 2022Comments
-
Ali almost 2 years
I'm trying to retrieve numeric values from a
DataGridView
. So far, the only way I've found is to retrieve them as a string and convert them to numeric.Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());
There must be an easier way. The cell is originally populated from a
DataSet
with a numeric field value but since theDataGridViewCell
object returns it as an object, I can't do a straight assignment. I must be missing something simple here.Thanks.
-
Marc Gravell over 15 yearsIt is the .Value you need to cast, not the DataGridViewCell itself.
-
Marc Gravell over 15 yearsSince the ValueType is a Type, you can't cast directly to the ValueType; however, you can check the Type is something you expect, though - but "is" might do just as well (nulls not withstanding).
-
Leon Tayson over 15 yearsyep, am so sleepy when i typed my reply. :)