【问题标题】:Prevent DataGridView selecting a row when sorted if none was previously selected如果之前未选择任何行,则防止 DataGridView 在排序时选择一行
【发布时间】:2009-09-10 19:20:16
【问题描述】:

我有一个 datagridview,当用户通过单击列标题对其进行排序时,它可能会或可能不会选择行。如果选择了行,则没有问题,但如果选择了 0 行,则排序会自动选择一行(选择是一致的,但我不知道标准是什么)。我怎样才能防止这种行为发生。

如果相关,则 DGV 没有数据绑定并且启用了全行选择。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    处理DataGridView的Sorted事件:

    this.dataGridView1.Sorted += new System.EventHandler(dataGridView1_Sorted);
    
    void dataGridView1_Sorted(object sender, System.EventArgs e)
    {
        dataGridView1.ClearSelection();
    }
    

    【讨论】:

    • 这也将清除我想要保留的现有用户选择。在执行排序之前似乎没有触发事件,就像关闭表单时(FormClosing 和 FormClosed)一样,我可以使用它来检查状态以确定之后是否应清除选择。跨度>
    • CellMouseDown 事件在排序之前触发,可用于检查选择状态。看起来更有可能的 ColumnHeaderClick 事件在排序后触发并且没用。
    • 需要的附加代码是:bool selectionsMade = false; private void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if ((e.Button == MouseButtons.Left) && (e.RowIndex == -1)) { selectionsMade = (((DataGridView)sender).SelectedRows.Count > 0 ); } }
    • 您提到的额外处理代码是否解决了您的问题?
    • 是的,将它与您的排序事件结合起来确实解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2011-12-30
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多