How To Search Records In DataGridView Using C#

 
Let's begin.

Create a new Windows Forms application.
 
 
Create a database (named Sample). Add a table, tbl_Employee. The following is the table schema for creating tbl_Employee.
 
 
Create a form (named frmSearch) and Drop Label, TextBox and DataGridView control from the ToolBox.
 
 
Now, go to the frmSearch.cs code and add the System.Data and System.Data.SqlClient namespaces. The following is the frmSearch.cs code:
  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.SqlClient;  
  5.   
  6. namespace SearchRecord  
  7. {  
  8.     public partial class frmSearch : Form  
  9.     {  
  10.         //Connection String  
  11.         string cs = "Data Source=.;Initial Catalog=Sample;Integrated Security=true;";  
  12.         SqlConnection con;  
  13.         SqlDataAdapter adapt;  
  14.         DataTable dt;  
  15.         public frmSearch()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.         //frmSearch Load Event  
  20.         private void frmSearch_Load(object sender, EventArgs e)  
  21.         {  
  22.             con = new SqlConnection(cs);  
  23.             con.Open();  
  24.             adapt = new SqlDataAdapter("select * from tbl_Employee",con);  
  25.             dt = new DataTable();  
  26.             adapt.Fill(dt);  
  27.             dataGridView1.DataSource = dt;  
  28.             con.Close();  
  29.         }  
  30.         //txt_SearchName TextChanged Event  
  31.         private void txt_SearchName_TextChanged(object sender, EventArgs e)  
  32.         {  
  33.             con = new SqlConnection(cs);  
  34.             con.Open();  
  35.             adapt = new SqlDataAdapter("select * from tbl_Employee where FirstName like '"+txt_SearchName.Text+"%'", con);  
  36.             dt = new DataTable();  
  37.             adapt.Fill(dt);  
  38.             dataGridView1.DataSource = dt;  
  39.             con.Close();  
  40.         }  
  41.     }  
  42. }  
In the preceding code, we have created a frmSearch_Load event for displaying the tbl_Employee data in the DataGridView when the form loads.

The txt_SearchName_TextChanged event fires when the text of the txt_SearchName TextBox changes.
 
Final Preview

 
I hope you will like it. Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all