简体   繁体   English

C#:如何获取未绑定的DataGridView单元的值?

[英]C#: How do I get the value of an unbound DataGridView cell?

I'm fairly newbie at C#. 我是C#的新手。 I've seen questions answering how to set values in an unbound grid. 我看到了一些问题的答案,这些问题解答了如何在无界网格中设置值。 Which seems to work. 这似乎可行。 But, to get the value back out doesn't seem to. 但是,收回价值似乎并没有。 I did try searching for the answer. 我确实尝试寻找答案。

I have an unbound DataGridView, named analogGrid. 我有一个未绑定的DataGridView,名为AnalogGrid。 Data is stored in an external class RTUdata. 数据存储在外部类RTUdata中。 It is a very simple grid, first column is read only with the row number. 这是一个非常简单的网格,第一列仅读取行号。 Second value is a value the user can change which should store it back into RTUdata. 第二个值是用户可以更改的值,应将其存储回RTUdata中。 Loading the data into the grid seems to work fine with this method: 使用以下方法将数据加载到网格中似乎可以正常工作:

private void loadAnalog()
{
    analogGrid.RowCount = RTUdata.getAnalogCount(RTUdata.getRTUaddr());
    for (UInt16 i = 0; i < RTUdata.getAnalogCount(RTUdata.getRTUaddr()); i++)
    {
        analogGrid.Rows[i].Cells[0].ValueType = typeof(System.UInt16);
        analogGrid.Rows[i].Cells[0].Value = i;
        analogGrid.Rows[i].Cells[1].ValueType = typeof(System.Int32);
        analogGrid.Rows[i].Cells[1].Value = RTUdata.getAnalogValue(RTUdata.getRTUaddr(), i);
    }
}

I'm not quite certain which event I should hook into as far as when to grab the value that the user entered and put it back into RTUdata. 我不确定应该何时捕获用户输入的值并将其放回RTUdata中。 But, I'm guessing it would be CellValidated(). 但是,我猜可能是CellValidated()。 So, I have this code: 所以,我有这段代码:

private void analogGrid_CellValidated(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex != 1)
        return;

    Int32 value = (Int32)binaryGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    RTUdata.setAnalogValue(RTUdata.getRTUaddr(), e.RowIndex, value);        
}

But, on the line 但是,就行

Int32 value = (Int32)binaryGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

I get a runtime error of "System.InvalidCastException: 'Specified cast is not valid.'" As far as I can tell, "Value" should be Int32, I set the value type when I load the grid. 我收到“ System.InvalidCastException:'指定的转换无效”的运行时错误。据我所知,“值”应为Int32,在加载网格时设置值类型。 So, why isn't the cast valid? 那么,为什么强制转换无效?

Thanks for any help! 谢谢你的帮助!

You're probably trying to cast a string value to int, which won't work. 您可能正在尝试将字符串值转换为int,这将无法正常工作。 Instead, convert it with .ToString() . 而是使用.ToString()转换。

Try this: 尝试这个:

Int32 value = Int32.Parse(binaryGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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