简体   繁体   中英

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?

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM