简体   繁体   中英

How to multiselect DataGridView rows without pressing CTRL key in c#?

I am new to c# and using windows forms.

I have a DataGridView control on a form and I need to allow a user to multi-select rows without pressing the CTRL key and without using check box column. I have already enabled the mutli-select property.

I know this is duplicated question on Here but I tried the first answer (Bolu answer) and it worked but the datagridvied refreshes and flicks every time I select a row.

I wanted to try the "Edit: Better solution" (in the same answer) and it is too complicated for me I did not understand the steps.

My question: How can I get rid of the flicking/ refreshing process and make it smooth when I select a row? (the code shown below), also I am happy to receive any new solutions. Please help me, thank you

DataGridViewRow[] old;
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    old = new DataGridViewRow[dataGridView1.SelectedRows.Count];
    dataGridView1.SelectedRows.CopyTo(old, 0);
}

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    foreach (DataGridViewRow gr in old)
    {
        if (gr == dataGridView1.CurrentRow)
        {
            gr.Selected = false;
        }
        else
        {
            gr.Selected = true;
        }
    }
}

Try this; keep the datagridview ( dgvTopics in my case) mutiselect true :

private void dgvTopics_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (dgvTopics.Rows[e.RowIndex].Selected == true)
        dgvTopics.Rows[e.RowIndex].ErrorText = "U";
    else
        dgvTopics.Rows[e.RowIndex].ErrorText = "S";  
}

private void dgvTopics_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
    foreach (DataGridViewRow dgvr in dgvTopics.Rows)
    {
        if(dgvr.ErrorText == "S")
            dgvr.Selected = true;
        else
            dgvr.Selected = false;
    }
}

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