如何在 DataGridView 中以编程方式设置单元格值? [英] How to programmatically set cell value in DataGridView?
问题描述
我有一个 DataGridView.一些单元从串行端口接收它们的数据:我想将数据推送到单元中,并让它更新底层绑定对象.
I have a DataGridView. Some of the cells receive their data from a serial port: I want to shove the data into the cell, and have it update the underlying bound object.
我正在尝试这样的事情:
I'm trying something like this:
SetValueFromSerial (decimal newValue)
{
dataGridView.CurrentCell.Value = newValue;
}
使用字符串无济于事:
dataGridView.CurrentCell.Value = newValue.ToString ();
在这两种情况下,我都没有在网格中看到任何东西,并且基础值没有变化.
In both cases, I don't see anything in the grid, and the underlying value is unchanged.
我在谷歌搜索并在这里搜索,但我没有找到任何东西.(我可能漏掉了一些东西,也许是一些显而易见的东西,但我并不完全懒惰.)
I did Google and search here, but I didn't find anything. (I may have missed something, perhaps something obvious, but I'm not utterly lazy.)
推荐答案
如果 DataGridView
是数据绑定的,则不应直接修改单元格的内容.相反,您应该修改数据绑定对象.您可以通过 DataGridViewRow
的 DataBoundItem
访问该对象:
If the DataGridView
is databound, you shouldn't directly modify the content of the cell. Instead, you should modify the databound object. You can access that object through the DataBoundItem
of the DataGridViewRow
:
MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;
obj.MyProperty = newValue;
注意绑定的对象应该实现INotifyPropertyChanged
,这样更改就会反映在DataGridView
Note that the bound object should implement INotifyPropertyChanged
so that the change is reflected in the DataGridView
这篇关于如何在 DataGridView 中以编程方式设置单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!