一列中搜索值的DataGridView [英] Search for value in DataGridView in a column
问题描述
我希望用户能够在在DataGridView(DGV)的柱以搜索一个数字。该DGV可以容纳多条记录。每个记录有一个项目编号。所以,我希望用户能够搜索栏项目编号项目数量。我的列有:专案编号(不可见);照片(不HEADERTEXT);项目编号;项目名;公司;联系
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?
我用来搜索代码来自的这个答案
The code I used to search comes from this answer
推荐答案
为什么你正在使用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屋!