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:
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.
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.
[Download Source Code via Google Drive]
This comment has been removed by the author.
ReplyDeleteGreat tutorials!!!1
ReplyDeleteThanks!but how about when were searching an Integer like an ID?
ReplyDeletethanks a lot for this code.. :)
ReplyDeleteThanks 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.
ReplyDeletethank you so much I have been trying things for the 5 past days finally got it right..
ReplyDelete