Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting DataKeyNames for row on button click

I have a gridview with buttons in each row:

enter image description here

The buttons are in a templatefield:

<asp:GridView ID="storyGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False" 
      BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"    
      CellSpacing="2" DataKeyNames="PK_NonScrumStory" DataSourceID="SqlDataSource1">
...
        <asp:TemplateField HeaderText="Actions">
            <ItemTemplate>
                <asp:Button ID="viewHoursButton" runat="server" Text="View Hours" OnClick="viewHoursButton_OnClick" />
                <asp:Button ID="addHoursButton" runat="server" Text="Add Hours" OnClick="addHoursButton_OnClick" />
                <asp:Button ID="editButton" runat="server" Text="Edit" OnClick="editButton_OnClick" />
                <asp:Button ID="deleteButton" runat="server" Text="Delete" OnClick="deleteButton_OnClick" />
            </ItemTemplate>
        </asp:TemplateField>

How do I get the data key name on click?

protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
    //get PK_NonScrumStory for clicked row
}
like image 726
David Tunnell Avatar asked Feb 20 '26 09:02

David Tunnell


2 Answers

I figured it out:

protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow row = btn.NamingContainer as GridViewRow;
    string pk = storyGridView.DataKeys[row.RowIndex].Values[0].ToString();
    System.Diagnostics.Debug.WriteLine(pk);
}
like image 158
David Tunnell Avatar answered Feb 22 '26 21:02

David Tunnell


You can bind CommandName and CommandArgument for your custom Buttons, for exemple:

<asp:Button ID="deleteButton" 
 runat="server" 
 Text="Delete" 
 CommandName="DeleteItem" 
 CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
 OnClick="deleteButton_OnClick" />

Then you should impletement the event storyGridView1_RowCommand, and treat every command:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "DeleteItem")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
     GridViewRow row = GridView1.Rows[index];

    //Retrieve the key of the row and delete the item

  }
  else if(e.CommandName == "EditItem")
  {
    //edit the item
  }
  //Other commands
}
like image 36
Fals Avatar answered Feb 22 '26 23:02

Fals