简体   繁体   English

如何在datagridview C#中使用shift和Ctrl键选择多行

[英]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. 我的要求:在datagridview中,我需要通过单击行标题来选择行,并且所选行应保持不变,直到我也将选择单元格的同时单击另一个行标题。

My Problem : I can't select multiple row using Shift and Ctrl key. 我的问题:我无法使用Shift和Ctrl键选择多行。

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. 重新考虑其中的if-else逻辑,您会明白为什么。 You are clearing your previous selections when you are not suppose to. 如果您不打算这样做,则正在清除以前的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM