Monday, February 02, 2015
Search 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(); 
        } 
    } 
} | 
Final Preview:
Hope you like it. Thanks.



