DataGridView.SelectedRows.Count始终= 0

时间:2013-12-20 17:03:22

标签: c# datagridview

我的应用程序中有一个datagridview。我希望能够选择一行或多行,然后右键单击并获取上下文菜单。上下文菜单中的选项将对所选行执行某些操作,例如隐藏它们。对于datagridview,我有multiselect = true和selectionmode = fullrowselect。出于某种原因,datagridview.selectedrows.count始终为= 0.为什么会这样?这是代码......

 private void Form1_Load(object sender, EventArgs e)
    {
        Image img = null;
        contextMenuStrip1.Items.Add("Hide selected", img, new System.EventHandler(contextMenuStrip1_Click));
        contextMenuStrip1.Items.Add("Unhide all", img, new System.EventHandler(contextMenuStrip1_Click));
        dataGridView1.ContextMenuStrip = contextMenuStrip1;
    }   

   private void contextMenuStrip1_Click(object sender, EventArgs e)
    {
        switch (sender.ToString().Trim())
        {
            case "Hide selected":
                //Necessary because a row with the current cell cannot be hidden.
                dataGridView1.CurrentCell = null;
                int count = dataGridView1.SelectedRows.Count;
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    row.Visible = false;
                }
                break;

            case "Unhide all":
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Visible = true;
                }
                break;
        }

    }

1 个答案:

答案 0 :(得分:3)

好的,所以我设置了一个快速项目来复制你遇到的问题。问题是您将dataGridView1.CurrentCell设置为null。执行此操作时,它会清除网格视图中的选定行。我注意到你在那里发表评论说它必须在那里。我不完全确定所有的逻辑和业务领域,但你需要找到另一种方法。使用此代码,我没有问题获取所选行:

switch (sender.ToString().Trim())
    {
        case "Hide selected":
            int count = dataGridView1.SelectedRows.Count;
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                row.Visible = false;
            }
            break;

        case "Unhide all":
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Visible = true;
            }
            break;
    }