繁体   English   中英

C#Winforms Datagridview单元验证

[英]C# Winforms datagridview cell validation

我有3列的datagridview:Guid(不可见),复选框列和字符串列。

我需要验证哪些用户输入了字符串列。 可能的情况:

1)不允许输入重复记录

2)不允许输入空白记录

需要记住的是:新行或编辑行。 例如,如果新行的空字符串被用户保留-我必须取消这个新行。

但是问题在于复选框列。 当我选中该复选框并保留它时(文本列为空)-我无法对其进行验证。 所以这是我的代码的瓶颈

 private void dgvKeywords_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (e.RowIndex < 0 || e.ColumnIndex != 2)
            return;

        string keyWord = e.FormattedValue == null ? string.Empty : e.FormattedValue.ToString();
        if (string.IsNullOrWhiteSpace(keyWord))
            if (!dgvKeywords.Rows[e.RowIndex].IsNewRow)
            {
                e.Cancel = true;
                MessageBox.Show("Keyword cannot be empty", "Keyword processing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        var list = bsCustomerLanguageKeywords.DataSource as List<CustomerLanguageKeyword>;
        if (list == null)
            throw new Exception("Unexpected type in the keywords grid");

        var separatedList = list.Where((t, i) => i != bsCustomerLanguageKeywords.Position).ToList();

        bool nonUnique = separatedList.Count(x => x.Word != null && x.Word.ToLower() == keyWord.ToLower()) > 0;
        if (nonUnique)
        {
            e.Cancel = true;
            MessageBox.Show("Keyword must be unique", "Keyword processing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
    }

不知道这是否是最佳实践(我很确定不是),但是我要做的是创建一种方法来验证需要验证的内容并将其放在几个事件上:UserAddedRow,Focus Leave和Focus行离开。 现在,您可以调试它并查看这3个事件中的哪一个首先触发并最符合您的情况,并将其保留为一个(或最多2个)。 但就我而言,我必须匆忙执行此操作,从此再也没有回到过:)。 祝你好运,让我知道是谁骗了这个;)

使用在DataGridViewCellValidatingEventArgs参数中传递给您的行和列索引来获取您所在位置的DataGridViewCell,然后根据最适合您的条件,访问单元格的Value属性或检查该单元格是否为复选框单元格并执行一些特殊情况的逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM