Reputation: 1171
I want to add a column to a gridview which contains button control. I am using ID(integer and primary key) as the 1st column of Gridview. What I want is that when a user clicks the button on any given row of gridview, I want to able to determine the ID of the row to which the clicked button belongs
Vam Yip
Upvotes: 2
Views: 1588
Reputation: 12493
To go along with @Midhat's answer, here is some sample code:
The code-behind:
public partial class _Default : System.Web.UI.Page
{
List<object> TestBindingList;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TestBindingList = new List<object>();
TestBindingList.Add(new { id = 1, name = "Test Name 1" });
TestBindingList.Add(new { id = 2, name = "Test Name 2" });
TestBindingList.Add(new { id = 3, name = "Test Name 3" });
this.GridView1.DataSource = TestBindingList;
this.GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
this.Label1.Text = this.GridView1.DataKeys[index]["id"].ToString();
}
}
}
The markup:
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
onrowcommand="GridView1_RowCommand" DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderText="ButtonColumn">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false"
CommandName="Select" Text="ClickForID"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
</form>
Upvotes: 1
Reputation: 17840
In the template for your grid view, bind The CommandArgument property of the button to the ID of the row. Then on the button click event, check the commandArgument property from the event args. This will give you the ID
Upvotes: 4