【发布时间】:2018-08-17 11:08:30
【问题描述】:
我有一个DataTable,其中包含一些数据,例如。像这样:
| id | name | type_id |
+-----+-------+---------+
| 0 | joe | 156 |
| 1 | alice | 23 |
DataTable 中的数据来自 SQL 数据库。我也有DataGridView,应该显示如下:
| name | type_name |
+-------+-----------+
| joe | admin |
| alice | user |
我有办法将type_id 查找到type_name。我添加了一个DataGridViewComboBoxColumn,当它发生变化时,我更新基础表中的type_id:
private void cellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// find the cell
DataGridViewCell cell = dataGridView[e.ColumnIndex, e.RowIndex];
string columnName = dataGridView.Columns[e.ColumnIndex]?.Name ?? "";
// check if combo cell is in this column for sure
if(cell is DataGridViewComboBoxCell comboCell)
{
// Only user type is subject to this event
if(columnName == "type_name")
{
// BIG NOTE: THE LOOKUP HERE COULD (and is) BE MORE COMPLEX!
// This is just an example for stack overflow
object cellVal = comboCell.Value;
// Only numeric values
// Combobox displays string names, but contains numeric values
if(cellVal!=null && IsNumber(cellVal))
{
// change the underlying datatable, not the grid view
dataTable.Rows[e.RowIndex]["type_id"] = cellVal;
}
}
}
}
但我也想要一个反之亦然的版本。当DataGridView 加载时,组合框列中的值为空。如何编写一段代码,将 DataTable 列中的值 映射到 DataGridView 列。
注意:在我的真实场景中,映射比数字->字符串更复杂。涉及多个值。因此必须真正创建新列!
【问题讨论】:
-
从我的测试来看,“IsNumber”函数在做什么还不清楚。如果组合框包含“admin”。 “user”等……然后当
object cellVal = comboCell.Value;行……总是会返回一个字符串“admin”“user”等。你说“我有办法将type_id查找到type_name”……但是我没有看到这一点。要点是,根据我对组合框的测试,IsNumber(cellVal)方法总是会失败,因为组合框的值不是数字。你能弄清楚“IsNumber”方法到底在做什么吗?
标签: c# .net winforms datagridview datatable