In this article I will explain with an example, how to get the ID of Button inside ASP.Net GridView when clicked using jQuery.
When the Button is clicked, a jQuery Click event handler will be called and the ID will be fetched and displayed using JavaScript Alert Message Box.
HTML Markup
The HTML Markup consists of an ASP.Net GridView with three BoundField columns and one TemplateField column.
The TemplateField column consists of a Button control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Customer Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespace.
Binding the GridView
Inside the Page Load event, the GridView is populated with a dynamic DataTable with some dummy records.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Getting ID of Button inside ASP.Net GridView when clicked using jQuery
Inside the jQuery document ready event handler, a Click event handler is assigned to all the Buttons inside the GridView.
When the Select Button inside the GridView Row is clicked, the clicked Button is referenced and the ID of the Button is determined.
Finally, the Button ID is displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=GridView1]").find("[id*=btnSelect]").click(function () {
//Reference the Button which was clicked.
var message = $(this).attr("id");
//Display the data using JavaScript Alert Message Box.
alert(message);
return false;
});
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads