您的位置:首页 > 其它

DataGridView 输入数据验证格式(实例)

2013-06-04 21:25 330 查看
在DataGridView属性里面添加dgvOne_CellValidating事件,然后根据需要以后。

private void dgvOne_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
//可编辑的列2、3、4、5、6(实际显示的列减1)列需要输入0~9的自然数.
if ( e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
{
int outDb = 0;
if (int.TryParse(e.FormattedValue.ToString(), out outDb))
{
e.Cancel = false;
}
else
{
e.Cancel = true;//数据格式不正确则还原
MessageBox.Show("请输入0~9的自然数!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvOne.CancelEdit();
}
}

//第二列验证时间格式
if (e.ColumnIndex == 1)
{
DateTime outDb =DateTime.Now;
if (DateTime.TryParse(e.FormattedValue.ToString(), out outDb))
{
e.Cancel = false;
}
else
{
e.Cancel = true;//数据格式不正确则还原
MessageBox.Show("输入日期格式不正确,请重新输入!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvOne.CancelEdit();
}
}

//第一列验证正整数

if (e.ColumnIndex == 0)
{
Regex notWholePattern = new Regex(@"^[0-9]\d*$");
if (notWholePattern.IsMatch(e.FormattedValue.ToString(), 0))
{
e.Cancel = false;
}
else
{
e.Cancel = true;//数据格式不正确则还原
MessageBox.Show("输入序号的格式不正确,请重新输入正整数!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvTwo.CancelEdit();
}
}

//长度验证

if (e.ColumnIndex == 6 || e.ColumnIndex == 7)
{
string str = e.FormattedValue.ToString();
int leng = str.Length;
if (leng > 1)
{
e.Cancel = true;//数据格式不正确则还原
MessageBox.Show("只能输入一位0~9的自然数,请重新输入!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvTwo.CancelEdit();

}
else
{
e.Cancel = false;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: