Introduction:
In this article, we'll explore a practical demonstration of how to leverage ASP.NET and jQuery to capture the click event on a GridView row and display the selected row's data in an alert. This interactive feature enhances user experience and provides a seamless way to access specific information from a grid.
Username | FirstName | LastName | Date-Of-Birth | Phone |
---|---|---|---|---|
MariaAnders | Maria | Anders | 24-04-1984 | 1234567890 |
AnaTrujillo | Ana | Trujillo | 04-08-1964 | 9876543210 |
AntonioMoreno | Antonio | Moreno | 01-12-1974 | 2222222222 |
ThomasHardy | Thomas | Hardy | 02-02-1984 | 5432167890 |
HTML Markup : Add Gridview Control
To begin, let's add a GridView control to the ASPX page:
<asp:GridView ID="tblGrid" runat="server">
</asp:GridView>
C# Coding : Bind GridView Control
Next, bind the GridView control with data from a database in the code-behind file. Begin by adding the necessary namespaces:
//Add namespace
using System.Data;
using System.Data.SqlClient;
Implement the page load event to call a private method, BindGridView():
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
SqlConnection con=new SqlConnection("Data Source=.; User ID=sa; Password=567334; Database=master;");
SqlDataAdapter da=new SqlDataAdapter("Select * from Customers",con);
DataSet ds=new DataSet();
da.fill(ds);
tblGrid.DataSource = ds;
tblGrid.DataBind();
}
jQuery : GridView Row Click Event
Now, let's use jQuery to capture the click event on a GridView row and display the selected row's data in an alert:
<script type="text/javascript">
$(document).ready(function(){
$("#tblGrid").on("click","tr", function(e){
var user = $(this).closest('tr').find('td:eq(0)').text();
var first = $(this).closest('tr').find('td:eq(1)').text();
var last = $(this).closest('tr').find('td:eq(2)').text();
var dob = $(this).closest('tr').find('td:eq(3)').text();
var phone = $(this).closest('tr').find('td:eq(4)').text();
alert('Username : '+user+'\nFirst Name : '+first+'\nLast Name : '+last+'\nDate Of Birth : '+dob+'\nContact No : '+phone);
});
});
</script>
Description:
This article provides a step-by-step guide on implementing GridView row click functionality. By hiding the GridView initially and enabling it through a "Demo Available" button, users can easily interact with the grid by clicking on any row to view detailed information in an alert.
The HTML markup, C# coding, and jQuery scripting work cohesively to create a seamless user experience. Developers can adopt this method to enhance interactivity in their ASP.NET applications, making data retrieval more intuitive and user-friendly. The demonstration serves as a practical guide for implementing this feature in real-world web development scenarios.
0 Comments