How do I find the row index on a button click in a gridview?

RD 40 Reputation points
2023-09-14T03:37:56.38+00:00

I have a gridview with a population of students. If there are reject reasons, a button appears in the last column of the gridview. When the button is clicked, I want to make a call to the database to get the reject reason codes. My button click event fires but I am having issues getting the row index or first name, last name in the row in which the button was clicked. How can I get the value of the cells where the button was clicked so I can pass those variables to the database?

Thanks!

My button code is:

                            <asp:TemplateField HeaderText="Incomplete Reason" >
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,892 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,860 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 45,271 Reputation points Microsoft Vendor
    2023-09-14T07:13:40.89+00:00

    Hi @RD , Welcome to Microsoft Q&A,

    Updated:

    If you want to get rowindex in Gridview of Asp.Net Web Form.

    Try using GridView_RowCommand.

    The official website has a good example.

    How to use the RowCommand event to add the name of a customer from a GridView control to a ListBox control when a row's Add button is clicked


    I showed how to use dataGridView1_CellClick to query various properties of the selected cell. In the example I show how to select only the type CheckBox.

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex > -1 && e.RowIndex > -1 && e.RowIndex < dataGridView1.Rows.Count)
        {
            var dc = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //Determine whether it is a CheckBox column
            if (dc.Value is bool cellValue)
            {
                MessageBox.Show($"RowIndex:{e.RowIndex} ColumnIndex:{e.ColumnIndex} Value:{cellValue}");
            }
        }
    }
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.