【问题标题】:DataGridView Lookup - Cannot Set Cell to String - Implicit Conversion to Int32?DataGridView 查找 - 无法将单元格设置为字符串 - 隐式转换为 Int32?
【发布时间】: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


【解决方案1】:

我设法自己解决了这个问题——尽管“解决”有点相对。我仍然对覆盖实际列的可能性感兴趣 - 但我的解决方案是创建一个新列。

  1. 向 DataGridView 添加一个新的未绑定列,名为“FieldName”。在我的示例中,列索引 0 是 FieldID 列,列索引 1 是新的 FieldName 列,当前为空。
  2. 根据列索引 0 的内容,通过字典查找修改列索引 1 的内容
  3. 隐藏列索引 0(在列属性 GUI 中执行此操作对我不起作用,所以我在代码中完成了)

相关代码:

foreach(DataGridViewRow row in dataGridView.Rows) {
    for(int i = 0; i < row.Cells.Count; i++) {
        int fieldID = Convert.ToInt32(row.Cells[0].Value);
        String fieldName = dictionary[fieldID];
        row.Cells[1].Value = fieldName;
    }
}
FieldColumn.Visible = false;

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多