简体   繁体   English

取消选择DataGridView上的所有行

[英]Unselect all rows on a DataGridView

Does anybody know how to unselect ALL the rows on a Windows Forms DataGridView control? 有谁知道如何取消选择Windows窗体DataGridView控件上的所有行? By default, the first row is always selected... 默认情况下,始终选择第一行...
Also, I don't want to allow any kind of selection, do you guys know any method to this? 另外,我不想允许任何选择,你们知道任何方法吗?

I've already searched here but can't find... 我已经在这里搜索但找不到......

Any help would be great! 任何帮助都会很棒!

Edit: Ok, I've found another way to unselect a row: on the DataGridViewRow.RowPostPaint() event, use the Selected property to unselect the row who sent the event. 编辑:好的,我找到了另一种取消选择行的方法:在DataGridViewRow.RowPostPaint()事件上,使用Selected属性取消选择发送事件的行。

private void grid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    this.gridLogEntries.Rows[e.RowIndex].Selected = false;
}

I don't think there's a simple solution like DisableSelection = true . 我认为没有像DisableSelection = true这样的简单解决方案。

Anyway, handling SelectionChanged event in the following way, should be enough: 无论如何,以下列方式处理SelectionChanged事件应该足够了:

private bool skipEvents;

void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (skipEvents)
        return;

    skipEvents = true;

    // disable cell selection
    foreach (DataGridViewCell cell in this.dataGridView1.SelectedCells)
        cell.Selected = false;
    // disable row selection
    foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        row.Selected = false;
    // disable column selection
    foreach (DataGridViewColumn col in this.dataGridView1.SelectedColumns)
        col.Selected = false;

    skipEvents = false;
}

EDIT: 编辑:

I slightly changed the code to avoid recursive calls of the method. 我略微更改了代码以避免方法的递归调用。

datagridview1.clearselection()

这将只在一个语句中解决问题,无需循环

尝试禁用tabstop选项,这对我来说是一个类似的问题

你试过这个吗?

myTable.CurrentRowIndex = -1;

You could try calling the unselect method for each selected row: 您可以尝试为每个选定的行调用取消选择方法:

        for (int i = 0; i < bindingSource1.Count; i++)
        {
            if (myGrid.IsSelected(i))
            {
                myGrid.UnSelect(i);
            }
        }

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

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