In this article I will explain how to call a JavaScript function on GridView Row click using jQuery in ASP.Net.
Using jQuery a Click event handler will be assigned to the GridView Row so that whenever the GridView Row is clicked the JavaScript function can be called.
HTML Markup
The HTML Markup consists of an ASP.Net GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Description" HeaderText="Description"
ItemStyle-Width="150" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespace.
C#
Binding the GridView control
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Description",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "Works as a scientist in USA.");
dt.Rows.Add(2, "Mudassar Khan", "ASP.Net programmer and consultant in India.");
dt.Rows.Add(3, "Suzanne Mathews", "Content Writer in France.");
dt.Rows.Add(4, "Robert Schidner", "Wild life photographer in Russia.");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Call JavaScript function on GridView Row click using jQuery
Inside the jQuery document ready event handler, a jQuery click event handler is assigned to the GridView Cell (TD element).
When any GridView Cell is clicked, first its parent Row is determined and is passed to the DisplayDetails JavaScript function which fetches the value of each cell of the GridView row and displays in JavaScript alert message box.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=GridView] td").click(function () {
DisplayDetails($(this).closest("tr"));
});
});
function DisplayDetails(row) {
var message = "";
message += "Id: " + $("td", row).eq(0).html();
message += "\nName: " + $("td", row).eq(1).html();
message += "\nDescription: " + $("td", row).eq(2).html();
alert(message);
}
</script>
Screenshot
Demo
Downloads