C# 在列中的 DataGridView 中搜索值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13173915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search for value in DataGridView in a column
提问by FJPoort
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.
我希望用户能够在 DataGridView (dgv) 的列中搜索数字。dgv 可以保存许多记录。每条记录都有一个项目编号。所以我希望用户能够在项目编号列中搜索项目编号。我拥有的列是: ProjectID(不可见);图像(无标题文本);项目编号; 项目名; 公司; 接触。
Here is my code:
这是我的代码:
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);
}
}
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.
问题 #1:到目前为止它做了什么:用户在 TextBox1 中键入项目编号。当他/她点击按钮时,代码在行中搜索这个字符串,当找到项目编号时,该行被选中。它工作正常,但只有一次。当我想搜索其他项目编号时,什么也没有发生。
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?
问题#2:我认为这可以通过仅搜索列项目名称的值以更好的方式完成。但是我应该如何正确地做到这一点?
The code I used to search comes from this answer
我用来搜索的代码来自这个答案
采纳答案by Danilo Vulovi?
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:
为什么要使用 row.Cells[row.Index]。您需要指定要搜索的列的索引(问题#2)。例如,您需要将 row.Cells[row.Index] 更改为 row.Cells[2] ,其中 2 是您的列的索引:
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);
}
}
回答by KB Gowda
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
回答by Rui Marques
Why don't you build a DataTablefirst then assign it to the DataGridViewas DataSource:
为什么不DataTable先构建一个然后将其分配给DataGridViewas DataSource:
DataTable table4DataSource=new DataTable();
table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");
...
(add your rows, manually, in a circle or via a DataReaderfrom a database table)
(assign the datasource)
(手动添加行,在圆圈中或通过DataReader数据库表中的 a)(分配数据源)
dtGrdViewGrid.DataSource = table4DataSource;
and then use:
然后使用:
(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();
You can even put this piece of code within your textbox_textchangeevent and your filtered values will be showing as you write.
您甚至可以将这段代码放在您的textbox_textchange事件中,您的过滤值将在您编写时显示。
回答by Hull
Filter the data directly from DataTableor Dataset:
直接从DataTable或过滤数据Dataset:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
Use this code on event KeyUpof Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.
在 事件KeyUp中使用此代码Textbox,将“MyTable”替换为您的表名或数据集,替换为您要搜索的字段。
回答by Mohamed Aitelhadj
"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;
"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;
How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?
与数据库连接和数据表的关系如何?我应该如何正确设置 DefaultView?
I use this code to get the data out:
我使用此代码来获取数据:
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\Users\mhadj\Documents\Visual Studio 2015\Projects\data_base_test_2\Sample.sdf";
con.Open();
DataTable dt = new DataTable();
adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
回答by achehab
It's better also to separate your logic in another method, or maybe in another class.
最好在另一种方法中或在另一个类中分离您的逻辑。
This method will help you retreive the DataGridViewCell object in which the text was found.
此方法将帮助您检索在其中找到文本的 DataGridViewCell 对象。
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}

