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.
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.
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
asked Nov 1, 2012 at 9:09
0
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);
}
}
answered Nov 1, 2012 at 9:19
2
Why don’t you build a DataTable
first then assign it to the DataGridView
as 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 DataReader
from a database table)
(assign the datasource)
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_textchange
event and your filtered values will be showing as you write.
answered Jun 30, 2014 at 22:13
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.
/// <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
}
}
answered Feb 15, 2017 at 16:39
// 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);
}
}
answered Jan 8, 2014 at 10:11
Filter the data directly from DataTable
or Dataset
:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
Use this code on event KeyUp
of Textbox
, replace «MyTable» for you table name or dataset, replace for the field where you want make the search.
answered Aug 7, 2014 at 18:03
«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?
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();
ManoDestra
6,3166 gold badges26 silver badges50 bronze badges
answered Apr 12, 2016 at 15:16
1
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
string searchValue = txtSearch.Text;
string colName = dataGridView1.Columns[1].Name;//Column Number of Search
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
btnSearch_Click(null,null);
}
answered Jan 5, 2022 at 22:53
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearch.Text;
for (var i = 0; i <= dgvList.RowCount; i++)
{
for (var j = 0; j <= dgvList.ColumnCount; j++)
{
if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
{
Console.Writeline("found");
dgvList.Item(j, i).Selected = true;
return;
}
}
}
}
This method will search all rows and cells in the DataGridView, If result is true then select the row.
answered Apr 27, 2022 at 17:21
I’m can solve it simply:
public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
{
foreach (DataGridViewRow Row in dgv.Rows)
{
if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
return Row.Index;
}
return -1;
}
answered Sep 19, 2022 at 15:34
private void textBox3_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables["todo"].DefaultView;
dv.RowFilter = "topic LIKE '" + textBox3.Text + "%'";
dataGridView1.DataSource = dv;
}
answered Jan 9 at 10:28
OzlemOzlem
11 bronze badge
21 / 21 / 2 Регистрация: 14.10.2009 Сообщений: 202 |
|
1 |
|
30.10.2010, 12:52. Показов 93851. Ответов 34
Хочу добавить возможность поиска строки в DataGridView для своего проекта. Форма поиска есть во вложениях. Вопрос как реализовать поиск? Поиск должен работать так: мы вводим строку в форму поиска, нажимаем найти далее, и в основной форме в DataGridView должна выделится строка, ячейки которой (хотя бы одна частично) удовлетворяют условиям поиска. Фильтровать ничего не нужно, просто выделять строки с частичным совпадением данных в ячейках. Поиск по всем столбцам. Данные в DataGridView подгружаются из БД аксесс встроенным в VS способом. Как это можно реализовать? Миниатюры
3 |
kenny69 burning1ife 1461 / 1283 / 293 Регистрация: 21.09.2008 Сообщений: 3,438 Записей в блоге: 9 |
||||
30.10.2010, 15:41 |
2 |
|||
Сообщение было отмечено как решение Решение
23 |
21 / 21 / 2 Регистрация: 14.10.2009 Сообщений: 202 |
|
31.10.2010, 11:25 [ТС] |
3 |
kenny69, Большое спасибо! Вчера пол дня гуглил и везде даны сложные решения, а тут все просто и понятно.
0 |
0 / 0 / 0 Регистрация: 13.04.2012 Сообщений: 11 |
|
24.01.2013, 12:07 |
4 |
В этом коде выделить просто переходит к искомой строке.. как сделать что бы он еще прокрутил ползунок к этой строке, и выбрал её?
0 |
4088 / 3822 / 745 Регистрация: 18.05.2010 Сообщений: 9,331 Записей в блоге: 11 |
|
24.01.2013, 12:08 |
5 |
Установите, еще дополнительно свойство FirstDisplayedScrollingRowIndex
1 |
0 / 0 / 0 Регистрация: 13.04.2012 Сообщений: 11 |
|
24.01.2013, 12:43 |
6 |
Да, только не много не получается прикрутить это свойство..
0 |
Dzalek 2 / 2 / 0 Регистрация: 13.04.2013 Сообщений: 18 |
||||
14.04.2013, 16:49 |
7 |
|||
А можно усовершенствовать данный поиск и чтобы выводил только найденные строки в DataGridView, а остальные не показывал. Заранее благодарен!
0 |
212 / 212 / 73 Регистрация: 12.01.2011 Сообщений: 749 |
|
15.04.2013, 19:05 |
8 |
Можно, но это уже не поиск, а фильтр. В интернете полно примеров фильтрации.
0 |
2 / 2 / 0 Регистрация: 13.04.2013 Сообщений: 18 |
|
16.04.2013, 01:01 |
9 |
Хорошо тогда подскажите где ошибка, я организовываю вот такой фильтр Как мне еще суда добавить другие столбцы (покажите на примере: спасибо) Или может есть еще проще способ в котором регистр ен учитывается вообще??? Заранее благодарен.
0 |
5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
|
25.04.2013, 21:04 |
10 |
а в код это можно добавить?)
0 |
4088 / 3822 / 745 Регистрация: 18.05.2010 Сообщений: 9,331 Записей в блоге: 11 |
|
26.04.2013, 08:01 |
11 |
Можно.
0 |
5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
|
30.04.2013, 06:54 |
12 |
Можно. примерчик плиз)
0 |
2 / 2 / 0 Регистрация: 13.04.2013 Сообщений: 18 |
|
03.05.2013, 12:00 |
13 |
так что никто не поможет с примером, Пожалуйста!
1 |
blacl_cloak 5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
||||
10.05.2013, 12:57 |
14 |
|||
как сделать чтоб найденная строка выделялась например красным цветом и происходил переход в гриде к найденной строке?
0 |
kenny69 burning1ife 1461 / 1283 / 293 Регистрация: 21.09.2008 Сообщений: 3,438 Записей в блоге: 9 |
||||
15.05.2013, 00:39 |
15 |
|||
как сделать чтоб найденная строка выделялась например красным цветом
происходил переход в гриде к найденной строке их может быть несколько
0 |
5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
|
15.05.2013, 08:05 |
16 |
их может быть несколько ну вот например он нашел первую строку и перешел к ней, нажал еще раз кнопку и перешел к следующей найденой строке. вот как это можно сделать?
0 |
kenny69 burning1ife 1461 / 1283 / 293 Регистрация: 21.09.2008 Сообщений: 3,438 Записей в блоге: 9 |
||||
15.05.2013, 13:44 |
17 |
|||
а в чем у вас сложность?
0 |
5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
|
15.05.2013, 14:56 |
18 |
DataGridView1.CurrentCell = DataGridView1.Item(1, 5)//перейти к ячейке. у меня ошибка на Item.
0 |
kenny69 burning1ife 1461 / 1283 / 293 Регистрация: 21.09.2008 Сообщений: 3,438 Записей в блоге: 9 |
||||
15.05.2013, 16:01 |
19 |
|||
0 |
5 / 5 / 7 Регистрация: 31.03.2013 Сообщений: 226 |
|
15.05.2013, 16:05 |
20 |
всё равно ошибка именно на Item.
0 |
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.
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.
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
asked Nov 1, 2012 at 9:09
0
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);
}
}
answered Nov 1, 2012 at 9:19
2
Why don’t you build a DataTable
first then assign it to the DataGridView
as 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 DataReader
from a database table)
(assign the datasource)
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_textchange
event and your filtered values will be showing as you write.
answered Jun 30, 2014 at 22:13
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.
/// <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
}
}
answered Feb 15, 2017 at 16:39
// 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);
}
}
answered Jan 8, 2014 at 10:11
Filter the data directly from DataTable
or Dataset
:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
Use this code on event KeyUp
of Textbox
, replace «MyTable» for you table name or dataset, replace for the field where you want make the search.
answered Aug 7, 2014 at 18:03
«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?
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();
ManoDestra
6,3166 gold badges26 silver badges50 bronze badges
answered Apr 12, 2016 at 15:16
1
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
string searchValue = txtSearch.Text;
string colName = dataGridView1.Columns[1].Name;//Column Number of Search
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
btnSearch_Click(null,null);
}
answered Jan 5, 2022 at 22:53
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearch.Text;
for (var i = 0; i <= dgvList.RowCount; i++)
{
for (var j = 0; j <= dgvList.ColumnCount; j++)
{
if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
{
Console.Writeline("found");
dgvList.Item(j, i).Selected = true;
return;
}
}
}
}
This method will search all rows and cells in the DataGridView, If result is true then select the row.
answered Apr 27, 2022 at 17:21
I’m can solve it simply:
public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
{
foreach (DataGridViewRow Row in dgv.Rows)
{
if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
return Row.Index;
}
return -1;
}
answered Sep 19, 2022 at 15:34
private void textBox3_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables["todo"].DefaultView;
dv.RowFilter = "topic LIKE '" + textBox3.Text + "%'";
dataGridView1.DataSource = dv;
}
answered Jan 9 at 10:28
OzlemOzlem
11 bronze badge
- Remove From My Forums
-
Question
-
I am pasting data in a DGV and want to search the first column [0]. I am using textbox change the code i have so far only highlights the row I need it to only show the rows it equals. This is what I have so far.
private void tb_Search_TextChanged(object sender, EventArgs e) { string searchValue = tb_Search.Text; int rowIndex = -1; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; try { foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[0].Value.ToString().Contains(searchValue)) { rowIndex = row.Index; dataGridView1.ClearSelection(); row.Selected = true; dataGridView1.FirstDisplayedScrollingRowIndex = rowIndex; dataGridView1.Focus(); break; } } } catch (Exception) { MessageBox.Show("No solutions with that name."); } } } }
Booney440
-
Moved by
Thursday, July 9, 2020 1:45 PM
Winforms related
-
Moved by
Monday, February 02, 2015
In this Article, we will learn How to Search Record in DataGridView in C# Windows Form Application. In previous post, we saw How to Insert, Update and Delete Record in DataGridView C#.
Let’s Begin:
1. Create a new Windows Form Application.
2. Create Database (named as Sample). Add a Table tbl_Employee. The following is the table schema for creating tbl_Employee.
3. Create a form (named as frmSearch) and Drop Label, TextBox and DataGridView control from the ToolBox.
Now, go to frmSearch.cs code and add System.Data and System.Data.SqlClient namespace.
frmSearch.cs code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SearchRecord
{
public partial class frmSearch : Form
{
//Connection String
string cs = «Data Source=.;Initial Catalog=Sample;Integrated Security=true;»;
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
public frmSearch()
{
InitializeComponent();
}
//frmSearch Load Event
private void frmSearch_Load(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter(«select * from tbl_Employee»,con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//txt_SearchName TextChanged Event
private void txt_SearchName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter(«select * from tbl_Employee where FirstName like ‘»+txt_SearchName.Text+«%'», con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
}
In the above code, we have created frmSearch_Load Event for Displaying tbl_Employee Data in DataGridView when form loads. txt_SearchName_TextChanged Event fires when the Text of txt_SearchName TextBox changes.
Final Preview:
Hope you like it. Thanks.
[Download Source Code via Google Drive]