Reader Level:
ARTICLE

Filter DataGridView With the Text Entered in TextBox in WinForms

Posted by Santhosh Kumar Jayaraman Articles | Windows Forms C# July 28, 2012
In this article, let us see how to filter a DataGridView when we type some values in a textbox.
  • 1
  • 0
  • 28012
Download Files:
 

Introduction

In this article, let us see how to filter a DataGridView when we type some values in a textbox.

Using the code

  1. Create a new Windows application. Add a DataGridView and textbox control.

    WinForms1.jpg
     
  2. I have an XML file I will bind to a DataGridView:

    XML File 1

    <?xml version="1.0" standalone="yes" ?>
    - <NewDataSet>
    - <Table1>
      <Server>Server1</Server>
      <Database>Database1</Database>
      </Table1>
    - <Table1>
      <Server>Server2</Server>
      <Database>Database2</Database>
      </Table1>
    - <Table1>
      <Server>Server3</Server>
      <Database>Database3</Database>
      </Table1>
      </NewDataSet>

     

  3. Create two properties of type DataSet and DataView as follows:

    public DataSet ds
    {
        get;
        set;
    }
     
    public
    DataView dv
    {
        get;
        set;
    }
     
  4. In the Form Constructor, create an object of DataSet and DataView:

    public Form1()
    {
        InitializeComponent();
        ds = new DataSet();
       dv = new DataView();
    }
     
     
  5. Now in the form load, read the XML file and save the values into the dataset. Then load the tables into the DataView with the DataTable in the DataSet. Now bind this DataView to the DataGridView:

    private void Form1_Load(object sender, EventArgs e)
    {
        string path = "C:\\XMLFile1.xml";
        ds.ReadXml(path);           
        dv.Table = ds.Tables[0];
        dataGridView1.DataSource = dv;
    }

     
  6. Now in the text_changed property of the textbox, add the following code. Here I am filtering it by the column "Server":

    dv.RowFilter = "Server like '%" + textBox1.Text + "%'";
    dataGridView1.DataSource = dv;
     
  7. Run the application and check.

    a. Form Load:

    WinForms2.jpg

    b. Valid data in column server:

    WinForms3.jpg

    c. Invalid data in Column server:

    WinForms4.jpg

I have attached the complete source code also.

COMMENT USING

Trending up