Datagridview SelectedRows.Count is always zero when selecting last row

匆匆过客 提交于 2021-02-08 03:35:51

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/20967427/datagridview-selectedrows-count-is-always-zero-when-selecting-last-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!