简体   繁体   中英

how select multiple row using shift and Ctrl key in datagridview C#

在此处输入图片说明在此处输入图片说明 My requirement : In datagridview I need select row by clicking the row header and selected row should maintain until I will click the other row header also same time I should select cell too.

My Problem : I can't select multiple row using Shift and Ctrl key.

my code :

    List< DataGridViewRow> selectedRows = new List< DataGridViewRow>();

    void selectRows()
    {
        dataGridView1.SuspendLayout();
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            r.Selected = selectedRows.Contains(r);
        }
        dataGridView1.ResumeLayout();
    }

    private void dataGridView1_RowHeaderMouseClick(object sender,DataGridViewCellMouseEventArgs e)
    {
        DataGridViewRow clickedRow = dataGridView1.CurrentRow;

        if (selectedRows.Contains(clickedRow))
        {
            selectedRows.Remove(clickedRow);
        }
        else
        {
            selectedRows.Add(clickedRow);
        }
        selectRows();

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if ((row.Index != e.RowIndex) && !row.Selected)
            {
                row.DefaultCellStyle.BackColor = Color.White;
            }
            else
            {
                selectedRows.Remove(clickedRow);
                row.Selected = true;
                row.DefaultCellStyle.BackColor = Color.Blue;
            }
        }
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.DefaultCellStyle.BackColor == Color.Blue)
            {
                row.Selected = true;
            }
        }
    }

您必须设置为启用datagridview的multiselect dataGridView.MultiSelect = true;

Be familiar with using a debugger, you will be able to find out where the issue is.

You are clearing the selection in your loop

foreach (DataGridViewRow row in dataGridView1.Rows)
{
}

Rethink the if-else logic in it and you will see why. You are clearing your previous selections when you are not suppose to.

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