C# DataGridView验证

C# DataGridView验证,c#,C#,对于文本框,我有一个如下的数据验证方法: string allowedCharacterSet = "1234567890\b\n"; if (allowedCharacterSet.Contains(e.KeyChar.ToString()) == false) { e.Handled = true; } 其工作方式是,如果用户键入的字符不在allowedCharacterSet中,则该字符不会出现在文本框中,从而防止他们输入无效数据 我的问题是:如何将其应用于DataGr

对于文本框,我有一个如下的数据验证方法:

string allowedCharacterSet = "1234567890\b\n";

if (allowedCharacterSet.Contains(e.KeyChar.ToString()) == false)
{
        e.Handled = true;
}
其工作方式是,如果用户键入的字符不在allowedCharacterSet中,则该字符不会出现在文本框中,从而防止他们输入无效数据


我的问题是:如何将其应用于DataGridView?假设我有3个单元格,第一个是名字,所以我只想要字母表。第二个是数量整数,因此仅为数字。第三个是电子邮件地址,所以在allowedCharacterSet字符串中有数字、字母、句点和@符号。这些事情我可以很容易地完成,但由于您无法将按键事件附加到单个DataGridView单元格,我不确定该怎么做。

您必须在DataGridView单元格验证事件中应用它。下面是我做的一些示例,用于将值限制在0-100之间。您可以编辑验证

// validation on dgvLotDetail's Yield Column (only numeric and between 0 to 100 allowed)
    private void dgvLotDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dgvLotDetail.Rows[e.RowIndex].Cells[txtYield.Index].Value != null)
        {
            if (e.ColumnIndex == txtYield.Index)
            {
                int i;
                if ( !int.TryParse(Convert.ToString(e.FormattedValue), out i) ||
                    i < 0 ||
                    i > 100 )
                {
                    e.Cancel = true;
                    MessageBox.Show("Enter only integer between 0 and 100.");
                }
                else
                {
                }
            }
        }
    }
//对dgvLotDetail的产量列进行验证(仅允许数字且介于0到100之间)
私有void dgvLotDetail_CellValidating(对象发送方,DataGridViewCellValidatingEventArgs e)
{
if(dgvLotDetail.Rows[e.RowIndex].Cells[txtfield.Index].Value!=null)
{
if(e.ColumnIndex==txtYield.Index)
{
int i;
if(!int.TryParse(Convert.ToString(e.FormattedValue),out i)||
i<0||
i>100)
{
e、 取消=真;
Show(“仅输入0到100之间的整数”);
}
其他的
{
}
}
}
}

您可以使用CellValueChanged、CellClick或CellEndEdit事件。将上述内容与
Regex
结合起来,以匹配您的具体情况…@renamr CellEndEdit仅在用户离开该单元格时触发,不是吗?其他人的行为相似吗?