0
votes

I have a datagridview in my application. I want to be able to select one or more rows, then right mouse click and get a context menu. Options in the context menu will do something with the selected rows, like hide them for example. For the datagridview, I have multiselect=true and selectionmode=fullrowselect. For some reason, the datagridview.selectedrows.count is always = 0. Why might this be? Here is code...

 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

1 Answers

3
votes

Ok, so I have setup a quick project to duplicate the problem your having. The problem is that you're setting dataGridView1.CurrentCell to null. When you do this it wipes out the selected rows in the grid view. I noticed you have a comment in there that it must be there. I'm not totally sure of all the logic and business domain, but you need to find another method. With this code I had no issue getting the selected row(s):

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;
    }