【问题标题】:How to check if datagridview input type matches with the underlying data type in c#?如何检查datagridview输入类型是否与c#中的底层数据类型匹配?
【发布时间】:2015-01-22 03:58:27
【问题描述】:

我想检查 datagridview 输入值类型是否与相应的单元格数据类型匹配。例如,如果我提供数字输入,它将检查相应的数据绑定 datagridview 列的数据类型是否为数字。如果字符串作为输入给出,那么它将显示错误消息,反之亦然。我试过这样:

private void dgvLoadTable_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
     if(e.FormattedValue.GetType() != dgvLoadTable.CurrentCell.ValueType.UnderlyingSystemType)
     MessageBox.Show("Input type is wrong"); }
}

但是即使输入正确,这也会显示错误消息。谁能告诉我如何正确操作?

【问题讨论】:

  • e.FormattedValueobject,它用于传递用户输入(文本)。您可以尝试解析它以查看类型是否匹配。我在简单的switch 中使用固定列DataGridView(不可重新排序)和e.ColumnIndexCurrentCell.ValueType 也可以与 dynamic parsing 一起使用。

标签: c# winforms validation datagridview


【解决方案1】:

我已经分析了你的源代码。一切对我来说都很好。也许您的数据源中有错误?

public partial class Form1 : Form
{
    private BindingList<Class> DataSource = new BindingList<Class>();

    public Form1()
    {
        InitializeComponent();            
        dgvLoadTable.DataSource = DataSource;            
    }

    private void dgvLoadTable_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (e.FormattedValue.GetType() != dgvLoadTable.CurrentCell.ValueType.UnderlyingSystemType)
            MessageBox.Show("Input type is wrong");
    }
}

public class Class
{
    public string StringData { get; set; }
    public int IntData { get; set; }
}

【讨论】:

    【解决方案2】:

    问题在于 Value 与 FormattedValue 或 ValueType 与 FormattedValueType 之间的差异。 ValueType 是列的真实类型。 FormattedValueType 是网格用来显示用户输入的值或类型的类型。如果您有一个整数行,则该值将格式化为字符串。同样:如果你输入一个整数,你只需输入一个字符串,该字符串被网格解析为整数。因此很难以这种方式执行您想要的检查,因为您的所有输入都是字符串,很难确定您的意思是 1 还是“1”。

    使用 DataGrid 的 DataError 事件对错误输入做出反应。 (例如整数列中的字母)

    【讨论】:

    • 我使用实体模型作为数据源,所以 DataError 事件不起作用。
    【解决方案3】:

    e.FormattedValue.GetType() 会为DataGridViewTextBoxColumn 返回String(例如DataGridViewImageColumn 会返回System.Drawing.Bitmap),和dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValueType 一样,是只读的。要设置列的类型,您可以这样做:

    myColumn.ValueType = typeof(int);
    

    然后,您可以订阅DataError 事件,而不是CellValidating 事件(只要用户输入单元格的数据或应用程序错误,就会引发该事件)。 (当列中的数据绑定到datasource时,ValueType默认分配给绑定数据的类型)

     void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
            {
                // process your data error here
                Console.WriteLine(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ValueType + "\n" + e.Exception); 
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 2011-05-03
      • 1970-01-01
      • 2011-11-28
      • 2022-12-04
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多