XXX*_*XXX 37 c# datagridview winforms
我有一个DataGridView.一些单元从串口接收数据:我想将数据推入单元,并让它更新底层绑定对象.
我正在尝试这样的事情:
SetValueFromSerial (decimal newValue)
{
dataGridView.CurrentCell.Value = newValue;
}
Run Code Online (Sandbox Code Playgroud)
使用字符串没有帮助:
dataGridView.CurrentCell.Value = newValue.ToString ();
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都没有在网格中看到任何内容,并且基础值没有变化.
我在谷歌搜索并在这里搜索,但我没有找到任何东西.(我可能错过了一些东西,也许是显而易见的东西,但我并不是完全懒惰.)
Tho*_*que 34
如果DataGridView是数据绑定,则不应直接修改单元格的内容.相反,您应该修改数据绑定对象.您可以通过访问该对象DataBoundItem的DataGridViewRow:
MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;
obj.MyProperty = newValue;
Run Code Online (Sandbox Code Playgroud)
请注意,绑定对象应该实现,INotifyPropertyChanged以便更改反映在DataGridView
如果您不想出于某种原因修改数据绑定对象(例如,您希望在网格中显示某些视图,但不希望它作为数据源对象的一部分),您可能希望这样做:
1.手动添加列:
DataGridViewColumn c = new DataGridViewColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
c.CellTemplate = cell;
c.HeaderText = "added";
c.Name = "added";
c.Visible = true;
dgv.Columns.Insert(0, c);
Run Code Online (Sandbox Code Playgroud)
2.在DataBindingComplete事件中执行以下操作:
foreach (DataGridViewRow row in dgv.Rows)
{if (row.Cells[7].Value.ToString()=="1")
row.Cells[0].Value = "number one"; }
Run Code Online (Sandbox Code Playgroud)
(只是一个愚蠢的例子)
但请记住,IT必须在DataBindingComplete中,否则值将保持空白
我搜索了如何插入新行以及如何像 Excel 一样设置其中单元格的各个值的解决方案。我用以下代码解决了:
dataGridView1.ReadOnly = false; //Before modifying, it is required.
dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!
Run Code Online (Sandbox Code Playgroud)
笔记:
希望这可以帮助你。
| 归档时间: |
|
| 查看次数: |
212614 次 |
| 最近记录: |