2
votes

I have a DataGridView in my Form. The Functionality is as below.

  • Clicking on header selects the whole column.
  • Clicking on any cell other than the column header selects the entire row

I have set multiselect to true. I am able to select multiple cells by using the mouse. but I want to do it programmatically.

2

2 Answers

7
votes

If you have multiselect true for your DataGridView then you can loop through the grid and the set the desired row as Selected

(Also your dataGridView.SelectionMode should be FullRowSelect)

dataGridView.Rows[0].Selected = true;//determine index value from your logic
dataGridView.Rows[5].Selected = true;

EDIT

Instead of row select then you can try this logic, subscribe to the rowheaderclick event wherein you would get the row index for which it was clicked, now loop through the columns and set each cell as selected (similar to above)

In the same way for the HeaderClick event you would have the column index available, now loop row wise and set the row indexes selected.

datagridview1[columnindex, rowindex].Selected = true

For rows the rowindex would be fixed whereas for column select the columnindex would be fixed.

Hope this helps you.

0
votes

It's important to allow the DataGridView to complete loading its data before attempting to select (multiple) items. You can do that in the DataBindingComplete event handler. Here's a working example:

    List<int> items = new List<int>() { 2, 4 };
    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        dataGridView1.ClearSelection();

        int lastItem = 0; // Save the last match to scroll to it later
        bool cellSelected = false;

        for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
        {
            if (items.Contains((int)dataGridView1.Rows[i].Cells[0].Value))
            {
                lastItem = i;

                dataGridView1.Rows[i].Selected = true;

                if (!cellSelected) // gotta select only one cell
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
                    cellSelected = true;
                }
            }
        }

        dataGridView1.FirstDisplayedScrollingRowIndex = lastItem;
    }