从DataGridViewCell获取数值?

时间:2020-03-06 14:56:37  来源:igfitidea点击:

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

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

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

谢谢。

解决方案

我们遇到的错误是什么? Convert.ToDouble有一个带有对象的重载方法,因此我们不需要ToString()吗?除非我们正在执行" TryParse"?

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;

由于" DataGridViewCell.Value"是一种对象类型,因此我们确实需要将其转换为适当的类型(" Double"或者任何"数字"类型)。 DataGridView的内容不是强类型的,因此我们必须转换从其单元格中检索到的值。

使用DataGridViewCell,我们可以将.Value强制转换为已知类型。以下是一个完整的示例,该示例通过" DataTable"(如示例)显示了这种情况(使用两次)。
另外,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);

    }
}

实际上,我最近刚刚处理了这个问题,我认为" TryParse"是我们在健壮性方面的最佳选择,但不要忘记检查Cell中的值是否为" null",否则,TryParse将失败。并抛出一个错误。

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

我还建议避免直接转换,除非我们完全知道要转换的类型,并且实际上在那里会有一个值,否则可能会在某个时候导致代码错误。