如何在c#windows应用程序中验证datagridview列? [英] How to validate datagridview column in c# windows application ?

查看:77
本文介绍了如何在c#windows应用程序中验证datagridview列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨先生,我想为每个条目验证datagridview第一列。例如,column1 Name = Name。因此,对于每一行必须有名称,没有名称,下一行不允许输入任何内容。

解决方案

你要在离开行或单元格时验证这一点选择放置此验证的位置非常重要。



我会使用 dataGridView1_CellValidating 方法或 dataGridView1_RowValidating 方法。



您在代码中遗漏的位 - 如果找到空白单元格,则需要设置 DataGridViewCellValidatingEventArgs.Cancel DataGridViewCellCancelEventArgs.Cancel 属性为true - 这将阻止您在输入有效数据之前移动到下一个单元格或行。



例如:

< pre lang =cs> private void dataGridView1_CellValidating( object sender,DataGridViewCellValidatingEventArgs e)
{
var x = dataGridView1.Rows [e.RowIndex] .Cells [e.ColumnIndex] .EditedFormattedValue.ToString();
// NB不使用.Value,因为它不会被设置(已提交)

if (x.Length == 0
{
MessageBox.Show( 您必须输入值);
e.Cancel = true ;
}
}





注意:你可以陷入一种无法关闭的僵局表单,直到有效数据输入所有单元格 - 这是一个惹恼用户的可靠方法!



我的提示 http://www.codeproject.com/Tips/777560/Allow-Form-to-close-when-invalid-data-is-present [ ^ ]进一步解释有几种方法可以解决这个特定问题。


Hi Sir,i want to validate datagridview first column for every entry.for example, column1 Name=Name. so for every row must have name,without name ,next row wont allow to enter anything.

解决方案

You want to validate this as you leave the row or the cell so the choice of where you put this validation is important.

I would use the dataGridView1_CellValidating method or the dataGridView1_RowValidating method.

The bit that you have missed in your code - If you find a blank cell you need to set the DataGridViewCellValidatingEventArgs.Cancel or DataGridViewCellCancelEventArgs.Cancel property to true - this will prevent you from moving to the next cell or row until valid data has been entered.

For example:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    var x = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();
    // NB do not use .Value as it will not be set (committed) yet

    if (x.Length == 0)
    {
        MessageBox.Show("You must enter a value");
        e.Cancel = true;
    }
}



Note: You can get yourself into a sort of deadlock where you can't close the form until valid data has been entered into all of the cells - this is a sure way to annoy your users!

My tip http://www.codeproject.com/Tips/777560/Allow-Form-to-close-when-invalid-data-is-present[^] explains this further with a couple of ways around it - there may well be better explanations/solutions for that particular problem out there though.


这篇关于如何在c#windows应用程序中验证datagridview列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆