Search records in GridView using asp.net c#

Asp.Net GridView control is one of the most versatile tools web developers used on their websites or web applications. It is easy to use and it comes with many useful features. In one of my previous articles, I have written about how to edit, update and delete records in a GridView control using Asp.Net. What I have missed is a discussion on how we can insert new records in a database table using a GridView or how to add new row in GridView control.

Now see example of Search records in GridView using asp.net c#

Step 1:  Create Database

CREATE TABLE [dbo].[Reg] (
[Id]      INT           IDENTITY (1, 1) NOT NULL,
[Name]    NVARCHAR (50) NOT NULL,
[RollNo]  NVARCHAR (50) NOT NULL,
[Address] NVARCHAR (50) NOT NULL,
[Class]   NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Step 2: Design the Webform.aspx as following

Search records in GridView using asp.net c#

Step 3 : code in  code behind file

public partial class WebForm1 : System.Web.UI.Page
{
SqlDataAdapter da;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
SqlConnection con = new SqlConnection();
ds = new DataSet();
con.ConnectionString = (@”Data Source=(LocalDB)\MYDB.mdf;Integrated Security=True“);
SqlCommand cmd = new SqlCommand(“SELECT * FROM Reg WHERE Name Like ‘%”+ txtSearch.Text + “%'”, con);

da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Regex.Replace(e.Row.Cells[0].Text, txtSearch.Text.Trim(),
delegate(Match match)
{
return string.Format(“{0}“, match.Value);
},
RegexOptions.IgnoreCase);
}
}

protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}

Run asp.net web project and see output
Search records in GridView using asp.net c#

SEE MORE