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
- How to create a table in SQL server?
- How to insert data in a table (manually or through insert script)
- Basics about controls like textbox, button and gridview.
- How to create website using visual studio?
- Basics about Jquery.
Steps Involved
- Create a table and add data in it
- Create the search text box
- Add columns in data grid on page load
- Add code to fetch value from database based on search keyword
- Add key press event for search textbox
- Run the program
Step 1. Create A Table And Add Data In It
Click to Enlarge
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
Click to Enlarge