Finding a value in a DataGridView in a column

I want the user to be able to search for a number in a column in a DataGridView (dgv). Dgv can store many records. Each entry has a project number. Therefore, I want the user to be able to find the project number in the Project Number column. I have columns: ProjectID (not visible); Image (no title); Project number; Project name; Company; Contact.

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 number 1:. What she is doing so far: the user enters the project number in TextBox1. When he / she presses the button, the code searches for this line in the lines, and when the project number is found, this line is selected. It works great, but only once. When I want to find another project number, nothing happens.

Problem # 2: I think this can be done better by looking up values ​​only for the Project Name column. But how do I do this properly?

The code I used to search is derived from this answer

+4
source share
6 answers

Why are you using row.Cells [row.Index]. You need to specify the index of the column that you want to find (problem number 2). For example, you need to change row.Cells [row.Index] to row.Cells [2], where 2 is the 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); } } 
+14
source
 // 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); } } 
0
source

Why don't you build the DataTable first, and then assign its DataGridView as a 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 through the DataReader from the database table) (assign a data source)

 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 in your textbox_textchange event, and your filtered values ​​will be displayed when recording.

0
source

Filter data directly from a DataTable or Dataset :

 "MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView; 

Use this code in the KeyUp event from Textbox , replace β€œMyTable” for the name of the table or dataset, replace for the field in which you want to search.

0
source

"MyTable" .DefaultView.RowFilter = "LIKE"% "+ textBox1.Text +"% "; this.dataGridView1.DataSource =" MyTable ".DefaultView;

What about the relationship with database connections and datatable? And how should I properly configure DefaultView?

I use this code to output data:

 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(); 
0
source

It is better to separate your logic in another method or, possibly, in another class.

This method will help you restore the DataGridViewCell object in which the text was found.

  /// <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 } } 
0
source

Source: https://habr.com/ru/post/1443389/


All Articles