C#可视化-Datagridview搜索,如果文本框=单元格字符串 [英] C# Visual - Datagridview search if textbox = cell string

查看:77
本文介绍了C#可视化-Datagridview搜索,如果文本框=单元格字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做到这一点,以便当您在 DataGridView 中输入数据时,它首先进行检查如果ID文本框包含 DataGridView ID列中存在的字符串,并且在找到匹配项时抛出错误.

I am trying to make it so that when you enter data into DataGridView it first checks if the ID textbox contains a string that exists in the DataGridView ID column and throws an error if it finds a match.

如果不匹配,则系统可以添加数据.

If it does not match then the system can add the data.

我尝试了各种各样的代码,使人们发布了无效的代码.这是我的最新消息.

I tried all kind of codes that people posted nothing worked. here is my latest.

private void btnadd_Click(object sender, EventArgs e)
{
    Label label25 = new Label();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells[0].Value.ToString() == IDtxtbox.Text)
        {
            label25.Text = "ID was already created,try some other number";
            break;
        }
        else
        {
            dataGridView1.Rows.Add(IDtxtbox.Text, Nametxtbox.Text);
            break;
        }
    }
}

推荐答案

在上面的代码中,如果第一行不包含该值,则说明您正在添加该值.

In the above code if the first row doesn't contain the value, you are adding the value.

您可以通过以下方式进行检查:

You can check it this way:

var exists= dataGridView1.Rows.Cast<DataGridViewRow>()
                         .Where(row => !row.IsNewRow)
                         .Select(row => row.Cells[0].Value.ToString())
                         .Any(x => this.IDtxtbox.Text == x);

if(!exists)
{
    //Add rows here
}

不要忘记使用System.Linq;

Don't forget to add using System.Linq;

这篇关于C#可视化-Datagridview搜索,如果文本框=单元格字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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