Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview SelectedRows.Count is always zero when selecting last row

I have a datagridview where I have set the allow user to add row property to false.

I have also made it only possible to have a fullrowselect on the datagridview.

A user adds rows to the datagrid by pressing the "+" button of the toolstrip. The DGV was created by dragging a datasourse to a form that added the binding navigator toolstrip.

My problem is that in my code for row deletion, i check

private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{
    try
    {
        if (dgvUsers.SelectedRows.Count > 0 && dgvUsers.Rows[0].Selected)
            MessageBox.Show("You cannot remove the user admin");
        else
        {
            if (MessageBox.Show("Are you sure you want to remove the user?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int code = 0;

                UserService userService = new UserService();

                if (dgvUsers.SelectedRows.Count > 0)
                {
                    int selectedrowindex = dgvUsers.SelectedCells[0].RowIndex;

                    DataGridViewRow selectedRow = dgvUsers.Rows[selectedrowindex];

                    code = (int)(selectedRow.Cells[0].Value);

                    if (GlobalClass.SessionId == "admin")
                    {
                        userService.RemoveUsers(code);
                    }
                    else
                        MessageBox.Show("Only username 'admin' can remove users");
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

When I select the last row for deletion, SelectedRows.Count = 0. But it is "1" when I select any other row. Why is this?

like image 426
Kinyanjui Kamau Avatar asked Sep 13 '25 21:09

Kinyanjui Kamau


1 Answers

Can you check if the "SelectionMode" property is set to FullRowSelect?

In the MSDN is written:

"The SelectionMode property must be set to FullRowSelect or RowHeaderSelect for the SelectedRows property to be populated with selected rows."

like image 76
Atanas Desev Avatar answered Sep 15 '25 10:09

Atanas Desev