从DataGridViewCell获取数值?

我正在尝试从DataGridView检索数值。 到目前为止,我发现的唯一方法是将它们作为字符串检索并将它们转换为数字。

 Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString()); 

必须有一个更简单的方法。 该单元最初是从具有数字字段值的DataSet填充的,但由于DataGridViewCell对象将其作为对象返回,因此我无法进行直接赋值。 我必须在这里错过一些简单的东西。

谢谢。

我实际上刚刚处理了这个问题, TryParse我认为这是你最好的稳健性,但不要忘记检查Cell中的null是否为null ,如果是这样, TryParse将失败并抛出错误。

 double d = 0; if(grid[col,row].Value != null) double.TryParse(grid[col,row].Value.ToString(), out d); 

我还建议避免直接转换,除非你完全知道你正在转换什么类型,并且事实上它会是一个值,它可能会在某些时候导致代码中的错误。

使用DataGridViewCell您可以将.Value为已知类型; 以下是一个完整的示例,它显示了DataTable (如您的示例)中发生的这种情况(使用double)。 此外, Convert.To{blah}(...)Convert.ChangeType(...)可能会有所帮助。

 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); } } 

DataGridViewCell具有ValueType属性。 您可以使用直接将值转换为该类型,而无需先将其转换为字符串:

 if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null && MyGrid.SelectedRows[0].Cells[0].ValueType == Double) return (Double)MyGrid.SelectedRows[0].Cells[0].Value; 

你得到的错误是什么? Convert.ToDouble有一个重载方法,它接受一个对象,所以你不需要ToString() ? 除非你在做TryParse

由于DataGridViewCell.Value是一个Object类型,因此您需要将它转换为适当的类型, Double或任何numeric类型。 DataGridView内容不是强类型的,因此您必须转换从其单元格中检索的值。