在列中的 DataGridView 中搜索值 [英] Search for value in DataGridView in a column

查看:35
本文介绍了在列中的 DataGridView 中搜索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户能够在 DataGridView (dgv) 的列中搜索数字.dgv 可以保存许多记录.每条记录都有一个项目编号.所以我希望用户能够在项目编号列中搜索项目编号.我拥有的列是:ProjectID(不可见);图像(无标题文本);项目编号;项目名;公司;联系方式.

I want the user to be able to search for a number in a column in the DataGridView (dgv). The dgv can hold many records. Each record has a Project Number. So I want the user to be able to search for a project number in column Project Number. The columns I have are: ProjectID(not visible); Image(no headertext); Project Number; Project Name; Company; Contact.

这是我的代码:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;
    int rowIndex = -1;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dgvProjects.Rows[row.Index].Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

问题 #1: 到目前为止的作用:用户在 TextBox1 中键入项目编号.当他/她点击按钮时,代码在行中搜索这个字符串,当找到项目编号时,该行被选中.它工作正常,但只有一次.当我想搜索其他项目编号时,什么也没有发生.

Problem #1: What it does so far: The user types the project number in TextBox1. When he/she clicks the button, the code searches for this string in the rows, and when found the project number, that row gets selected. It works fine, but only once. When I want to search for an other project number, nothing happens.

问题 #2: 我认为这可以通过仅搜索列项目名称的值以更好的方式完成.但是我应该如何正确地做到这一点?

Problem #2: I think this can be done in a better way, by searching the values for column Project Name only. But how should I do this properly?

我用来搜索的代码来自这个答案

推荐答案

为什么使用 row.Cells[row.Index].您需要指定要搜索的列的索引(问题 #2).例如,您需要将 row.Cells[row.Index] 更改为 row.Cells[2],其中 2 是您的列的索引:

Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

这篇关于在列中的 DataGridView 中搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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