Как в datagridview найти

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

Community's user avatar

asked Nov 1, 2012 at 9:09

FJPoort's user avatar

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

Danilo Vulović's user avatar

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.

Dan Is Fiddling By Firelight's user avatar

answered Jun 30, 2014 at 22:13

Rui Marques's user avatar

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

achehab's user avatar

//     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);
    }
}

Dan Is Fiddling By Firelight's user avatar

answered Jan 8, 2014 at 10:11

KB Gowda's user avatar

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.

Marvin Dickhaus's user avatar

answered Aug 7, 2014 at 18:03

Hull's user avatar

«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's user avatar

ManoDestra

6,3166 gold badges26 silver badges50 bronze badges

answered Apr 12, 2016 at 15:16

Mohamed Aitelhadj's user avatar

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

H.P's user avatar

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

Manoj Babu's user avatar

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

Hosserin Ibrahim's user avatar

  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

Ozlem's user avatar

OzlemOzlem

11 bronze badge

21 / 21 / 2

Регистрация: 14.10.2009

Сообщений: 202

1

30.10.2010, 12:52. Показов 93851. Ответов 34


Студворк — интернет-сервис помощи студентам

Хочу добавить возможность поиска строки в DataGridView для своего проекта. Форма поиска есть во вложениях. Вопрос как реализовать поиск? Поиск должен работать так: мы вводим строку в форму поиска, нажимаем найти далее, и в основной форме в DataGridView должна выделится строка, ячейки которой (хотя бы одна частично) удовлетворяют условиям поиска. Фильтровать ничего не нужно, просто выделять строки с частичным совпадением данных в ячейках. Поиск по всем столбцам. Данные в DataGridView подгружаются из БД аксесс встроенным в VS способом. Как это можно реализовать?

Миниатюры

Поиск строки в DataGridView
 



3



kenny69

burning1ife

1461 / 1283 / 293

Регистрация: 21.09.2008

Сообщений: 3,438

Записей в блоге: 9

30.10.2010, 15:41

2

Лучший ответ Сообщение было отмечено как решение

Решение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 private void button1_Click(object sender, EventArgs e)
        {
 
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Selected = false;
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                    if (dataGridView1.Rows[i].Cells[j].Value != null)
                        if (dataGridView1.Rows[i].Cells[j].Value.ToString().Contains(textBox1.Text))
                        {
                            dataGridView1.Rows[i].Selected = true;
                            break;
                        }
            }
        }



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



Эксперт Java

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

Цитата
Сообщение от kenny69
Посмотреть сообщение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 private void button1_Click(object sender, EventArgs e)
        {
 
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Selected = false;
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                    if (dataGridView1.Rows[i].Cells[j].Value != null)
                        if (dataGridView1.Rows[i].Cells[j].Value.ToString().Contains(textBox1.Text))
                        {
                            dataGridView1.Rows[i].Selected = true;
                            break;
                        }
            }
        }

А можно усовершенствовать данный поиск и чтобы выводил только найденные строки в 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

Хорошо тогда подскажите где ошибка, я организовываю вот такой фильтр
if(String.IsNullOrEmpty(PoiskGlavtextBox1.Text))
GlavbindingSource1.Filter = «»;
else
GlavbindingSource1.Filter = «([Марка ТС] LIKE'» + PoiskGlavtextBox1.Text + «%’)»;

Как мне еще суда добавить другие столбцы (покажите на примере: спасибо)
И как мне исключить зависимость от регистра (tolower)
не могу понять где его тут применить, Точнее чтобы совпали значения нужно введенное слово изменить регистр потом сравнимое в таблице слово изменить регистр и после этого только их сравнить,

Или может есть еще проще способ в котором регистр ен учитывается вообще???

Заранее благодарен.



0



5 / 5 / 7

Регистрация: 31.03.2013

Сообщений: 226

25.04.2013, 21:04

10

Цитата
Сообщение от turbanoff
Посмотреть сообщение

а в код это можно добавить?)



0



Эксперт Java

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

Цитата
Сообщение от turbanoff
Посмотреть сообщение

Можно.

примерчик плиз)



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

Цитата
Сообщение от kenny69
Посмотреть сообщение

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 private void button1_Click(object sender, EventArgs e)
        {
 
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Selected = false;
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                    if (dataGridView1.Rows[i].Cells[j].Value != null)
                        if (dataGridView1.Rows[i].Cells[j].Value.ToString().Contains(textBox1.Text))
                        {
                            dataGridView1.Rows[i].Selected = true;
                            break;
                        }
            }
        }

как сделать чтоб найденная строка выделялась например красным цветом и происходил переход в гриде к найденной строке?



0



kenny69

burning1ife

1461 / 1283 / 293

Регистрация: 21.09.2008

Сообщений: 3,438

Записей в блоге: 9

15.05.2013, 00:39

15

Цитата
Сообщение от blacl_cloak
Посмотреть сообщение

как сделать чтоб найденная строка выделялась например красным цветом

C#
1
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;

Цитата
Сообщение от blacl_cloak
Посмотреть сообщение

происходил переход в гриде к найденной строке

их может быть несколько



0



5 / 5 / 7

Регистрация: 31.03.2013

Сообщений: 226

15.05.2013, 08:05

16

Цитата
Сообщение от kenny69
Посмотреть сообщение

их может быть несколько

ну вот например он нашел первую строку и перешел к ней, нажал еще раз кнопку и перешел к следующей найденой строке. вот как это можно сделать?



0



kenny69

burning1ife

1461 / 1283 / 293

Регистрация: 21.09.2008

Сообщений: 3,438

Записей в блоге: 9

15.05.2013, 13:44

17

а в чем у вас сложность?
логику вы описали сами.

C#
1
DataGridView1.CurrentCell = DataGridView1.Item(1, 5)//перейти к ячейке.



0



5 / 5 / 7

Регистрация: 31.03.2013

Сообщений: 226

15.05.2013, 14:56

18

Цитата
Сообщение от kenny69
Посмотреть сообщение

DataGridView1.CurrentCell = DataGridView1.Item(1, 5)//перейти к ячейке.

у меня ошибка на Item.
«System.Windows.Forms.DataGridView» не содержит определения для «Item» и не был найден метод расширения «Item», принимающий тип «System.Windows.Forms.DataGridView» в качестве первого аргумента (возможно, пропущена директива using или ссылка на сборку)



0



kenny69

burning1ife

1461 / 1283 / 293

Регистрация: 21.09.2008

Сообщений: 3,438

Записей в блоге: 9

15.05.2013, 16:01

19

C#
1
DataGridView1.CurrentCell = DataGridView1.Item[1, 5];//перейти к ячейке.



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

Community's user avatar

asked Nov 1, 2012 at 9:09

FJPoort's user avatar

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

Danilo Vulović's user avatar

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.

Dan Is Fiddling By Firelight's user avatar

answered Jun 30, 2014 at 22:13

Rui Marques's user avatar

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

achehab's user avatar

//     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);
    }
}

Dan Is Fiddling By Firelight's user avatar

answered Jan 8, 2014 at 10:11

KB Gowda's user avatar

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.

Marvin Dickhaus's user avatar

answered Aug 7, 2014 at 18:03

Hull's user avatar

«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's user avatar

ManoDestra

6,3166 gold badges26 silver badges50 bronze badges

answered Apr 12, 2016 at 15:16

Mohamed Aitelhadj's user avatar

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

H.P's user avatar

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

Manoj Babu's user avatar

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

Hosserin Ibrahim's user avatar

  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

Ozlem's user avatar

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

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]

Понравилась статья? Поделить с друзьями:
  • Как найти длину отрезка через уравнение
  • Как найти роддом где родился
  • Как исправить сервер в мта
  • Как найти телевизор в сети на компьютере
  • Как исправить ошибки в приложениях на планшете