Articles → jQuery → Search gridview records using search textbox in asp.net and jQuery

Search gridview records using search textbox in asp.net and jQuery






Software





Technical knowledge















Steps Involved

















Step 1. Create a table and add data in it




Picture showing table schema of the sample table

Click to Enlarge



Picture showing the table data in the sample table

Click to Enlarge


Step 2. Create the search text box




Search:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:GridView ID="gvTest" runat="server"></asp:GridView>



Step 3. Add columns in datagrid on page load




protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) {
    DataTable dummy = new DataTable();
    dummy.Columns.Add("Class Name");
    dummy.Rows.Add();
    gvTest.DataSource = dummy;
    gvTest.DataBind();
  }
}



Step 4. Add code to fetch value from database based on search keyword




[WebMethod]
public static string GetNames(string classDisplayName) {
  DataSet ds = new DataSet("class");
  string query = string.IsNullOrWhiteSpace(classDisplayName) ? "SELECT ClassDisplayName FROM Class": string.Format("SELECT ClassDisplayName FROM Class where ClassDisplayName like '%{0}%'", classDisplayName);
  using(SqlConnection conn = new SqlConnection(@"conn_string")) {
    conn.Open();
    using(SqlDataAdapter adap = new SqlDataAdapter(query, conn)) {
      adap.Fill(ds);
    }

  }
  return ds.GetXml();
}



Step 5. Add key press event for search textbox




<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("#<%=txtSearch.ClientID %>").keyup(function() {
		//---
		$.ajax({
			type: "POST",
			url: "About.aspx/GetNames",
			data: "{classDisplayName:'" + $('#<%=txtSearch.ClientID %>').val() + "'}",
			contentType: "application/json",
			dataType: "json",
			success: function(response) {
				var xmlDoc = $.parseXML(response.d);
				var xml = $(xmlDoc);
				var student = xml.find("class").find("Table");
				$("#<%=gvTest.ClientID %>").html('');
				$("#<%=gvTest.ClientID %>").html('<table cellspacing="0" rules="all" border="1" id="<%=gvTest.ClientID %>" style="border-collapse:collapse;"><tr><th scope="col">Class Name</th></tr><tr><td> </td></tr></table>');
				var str = "";
				for(i = 0; i < student.length; i++) {
					str = str + "<tr><td>";
					str = str + $(student[i]).find("ClassDisplayName").text();
					str = str + "</td></tr>";
				}
				$("#<%=gvTest.ClientID %>").append(str);
			}
		});
		// ---
	});
});        
</script>



Step 6. Run the program




Picture showing the output of Search gridview records using search textbox in asp.net and jQuery

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, June 21, 2014

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250