0

I try to delete a record in Gridview and Database .I added a boundfield button and set the CommandName to Deleterecord in the RowCommand event I want to get the primary key of this record to delete that(primary key value does not show in the grid view. The following block of code shows this event(I try to show some data in a text box):

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "Deleterecord")
            {
                TextBox1.Text = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString(); 
                   //bla bla
            }
        }

I also set

DataKeyName="sourceName"

in the gridview but it is not my primary key

If I click this button an exception occured like this: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index How can I solve this problem

Baper
  • 1,533
  • 5
  • 22
  • 30
  • Possible duplicate of [Get DataKey values in GridView RowCommand](https://stackoverflow.com/questions/2818203/get-datakey-values-in-gridview-rowcommand) –  Jul 01 '17 at 14:51

1 Answers1

0

Use this

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Deleterecord")
    {
         LinkButton lb = (LinkButton)e.CommandSource;
         GridViewRow gvr = (GridViewRow)lb.NamingContainer;

         TextBox1.Text = grid.DataKeys[gvr.RowIndex].Value.ToString(); 
         //bla bla
    }
}

Here LinkButton should be replaced by the type of control which is performing this RowCommand Event

For more info go Here

Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42
yogi
  • 19,175
  • 13
  • 62
  • 92