尝试将gridview单元格值解析为任何类型(验证)

本文关键字:任何 类型 验证 gridview 单元格 | 更新日期: 2023-09-27 18:11:37

我试图验证用户在可编辑的gridview中输入的内容。我使用事件CellLeave验证输入,如下所示:

private void membersGrid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    // Datatable that will hold the schema for the Members table
    DataTable dtMeta;
    // SqlDataAdapter is already filled and is now used to get the metadata
    daAllMembers.FillSchema(dtMeta, SchemaType.Source);
    // Define a type instance of the current column from the metadata table dtMeta
    System.Type cellType = dtMeta.Columns[e.ColumnIndex].DataType;
    // Get an object from the editted cell
    Object objCellValue = membersGrid[e.ColumnIndex, e.RowIndex].Value;
    // This is where i'm stuck, how can I do this?
    cellType.TryParse(objCellValue);
}

我希望你明白我在努力做什么。我基本上想尝试将对象解析为该表的元数据中定义的类型。

尝试将gridview单元格值解析为任何类型(验证)

我假设您只想验证文本输入。其他单元格类型,如复选框或组合框,自然会限制用户输入。您可以执行以下操作:

  1. 创建一个派生自DataGridViewTextBoxCell的抽象类:

    公共抽象类MyTextBox: DataGridViewTextBoxCell{虚拟bool ValidateTextInput();}

  2. 为您想要验证的每种不同类型的数据网格视图单元格类型从这个基类派生一个类。例如:

    公共类StateCell: MyTextBox{覆盖ValidateTextInput (){//验证文本是否为有效的状态缩写}}

  3. 将自定义的验证数据网格视图单元格类型放入数据网格视图(http://msdn.microsoft.com/en-us/library/aa730881(v=vs.80).aspx)。