【发布时间】:2019-03-11 17:20:05
【问题描述】:
我正在开发一个显示表格的 DataGridView 的应用程序,如下所示:
FieldID | Value
---------------
1 | Jane
2 | Doe
我还有一个 Dictionary<int, String>,它可以让我从 FieldID 运行查找到字段名称的字符串版本(名字、姓氏等)
按照此处的建议 How to create LookUp fields in DataGridView?,我正在尝试将 FieldID 列中的单元格设置为 dictionary[fieldID] 查找。但是,当我设置 cell.Value 时,我收到以下错误(运行时错误,在我的 WinForms 应用程序中而不是 Visual Studio 中弹出):
The following exception occurred in the DataGridView:
System.Exception: First Name is not a valid value for Int32. ----->
System.FormatException: Input string was not in a correct format
at System.number.StringToNumber...
等等
设置单元格的代码如下:
String value = dictionary[cell.Value]; //value = "First Name"
cell.Value = value; //Error occurs on this line
我的问题是,我不知道 DataGridView 为何/在何处转换为 Int32 - 我从未明确声明包含 FieldID 的列是严格的 int。如果它确实以这种方式解释它,我已经尝试在将字符串值分配给单元格之前运行以下命令:
dataGridView.Columns[0].CellTemplate.ValueType = typeof(String);
和
cell.ValueType = typeof(String);
不过,两者似乎都没有任何区别。如何停止隐式转换为 int?
【问题讨论】:
-
dictionary[fieldID]给出字典中的字符串值。您应该只将第一个单元格的值设置为fieldID。 -
@ChetanRanpariya 它已经设置为仅
fieldID,我希望将其设置为字典中的字符串值。这就是目标。 -
您能分享给将单元格的值设置为
dictionary[fieldID]的代码吗?是第一个单元格还是第二个单元格? -
我已更新问题以包含我使用的确切代码,这实际上只是对设置
cell.Value的调用。cell是“第一个”单元格,这意味着我想将 FieldID 列中的所有 FieldID 从它们的 ID 号更改为它们的等效字符串。
标签: c# winforms datagridview