Majid Basirati
Majid Basirati

Reputation: 2855

retrieve data key of selected row in gridview in asp.net

I have a button (item template) in any rows of a gridView. I want when user clicks on this button, I retrieve dataKey of row that there is that button in it. how can I do this? (sorry,I can't speak and write English very well)

Upvotes: 0

Views: 3057

Answers (2)

Steve Wellens
Steve Wellens

Reputation: 20620

Assuming you have one DataKey and it is an int and the row of the button isn't necessarily selected and you have connected the following function to the buttons in your template field:

protected void RowClicked(object sender, EventArgs e)
{
    Button TempButton = sender as Button;

    if (TempButton != null)
    {
        GridViewRow GVR = TempButton.Parent.Parent as GridViewRow;

        if (GVR != null)
        {
           int ID = (int) GridView1.DataKeys[GVR.DataItemIndex].Value;
        }
    }
}

Upvotes: 1

Daniel Uribe
Daniel Uribe

Reputation: 778

Try the SelectedIndexChanged event. Something like this:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
     TextBox1.Text = GridView1.SelectedRow.Cells[1].Text;
     TextBox2.Text = GridView1.SelectedRow.Cells[2].Text;
     .
     .
     .
}

Upvotes: 0

Related Questions