C# 从 DataGridViewCell 获取数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/154697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 15:58:31  来源:igfitidea点击:

Get Numeric Value from DataGridViewCell?

提问by

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.

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

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

There must be an easier way. The cell is originally populated from a DataSetwith a numeric field value but since the DataGridViewCellobject returns it as an object, I can't do a straight assignment. I must be missing something simple here.

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

Thanks.

谢谢。

回答by JamesSugrue

What is the error you are getting? Convert.ToDoublehas an overloaded method that takes an object, so you shouldn't need the ToString()? Unless you are doing a TryParse?

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

回答by Vivek

DataGridViewCellhas ValueTypeproperty. You can use to do directly cast the value to that type without first converting it to string:

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;

回答by Leon Tayson

Since DataGridViewCell.Valueis an Object type, you really need to convert it to the appropriate type, Doubleor any numerictype in your case. The DataGridViewcontents aren't strongly typed so you have to cast the values retrieved from its cells.

由于DataGridViewCell.Value是 Object 类型,您确实需要将其转换为适当的类型,Doublenumeric您的情况下的任何类型。该DataGridView内容不是强类型的,所以你要投其细胞检索的值。

回答by Marc Gravell

With DataGridViewCellyou can just cast the .Valueto 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.

有了DataGridViewCell你可以只投了.Value你的已知类型; 以下是一个完整的示例,显示了来自 a 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);

    }
}

回答by Fry

I've actually just recently dealt with this problem and TryParseI 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 TryParsewill fail and throw up an error.

我实际上最近刚刚处理了这个问题,TryParse我认为这是关于稳健性的最佳选择,但不要忘记检查 Cell 中的值是否为null,如果是,TryParse则会失败并抛出错误。

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.

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