Check this sample using Northwind database
Id:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick = "Search" />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Contact Id" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Id" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT * FROM Customers";
string id = txtSearch.Text.Trim();
if (!string.IsNullOrEmpty(id))
{
id = string.Format(" where CustomerId = '{0}'", id);
}
SqlCommand cmd = new SqlCommand(query + id);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}