Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Monday 2 February 2015

Search Record in DataGridView C#

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]

6 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks!but how about when were searching an Integer like an ID?

    ReplyDelete
  3. thanks a lot for this code.. :)

    ReplyDelete
  4. Thanks for sharing this post. I'm very interested in this topic. more Check out this awesome useful online file converter that can come handy for use.

    ReplyDelete
  5. thank you so much I have been trying things for the 5 past days finally got it right..

    ReplyDelete

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook