c# - DataGridView 中的 CellClick 事件和 SelectionChanged 事件

标签 c# winforms events datagridview

Windows Froms DataGridView 控件中的 CellClick 事件和 SelectionChanged 事件有什么区别?

选择更改事件究竟何时运行:在表单加载事件之前还是之后?

最佳答案

此类问题的最佳引用是 MSDN DataGridView 文档。

对于CellClick他们说的事件:

This event occurs when any part of a cell is clicked, including borders and padding. It also occurs when the user presses and releases the SPACE key while a button cell or check box cell has focus, and will occur twice for these cell types if the cell is clicked while pressing the SPACE key.

对于SelectionChanged事件:

This event occurs whenever cells are selected or the selection is canceled, whether programmatically or by user action. For example, this event is useful when you want display the sum of the currently selected cells.

明显的区别在于,即使 DataGridView 选择没有改变,例如右键单击或单击当前选定的单元格时,CellClick 也可以触发。此外,选择可以在不单击单元格的情况下更改,例如,当您以编程方式更改选择时。

至于选择更改事件相对于表单加载事件的准确运行时间,当它附加到表单构造函数中时,它就在之前(并且在那个时候发生了几次!)。

我刚刚用下面的代码向自己证明了这一点:

public Form1()
{
    InitializeComponent();

    MyBindingList<BackingObject> backing_objects = new MyBindingList<BackingObject>();
    backing_objects.Add(new BackingObject{ PrimaryKey = 1, Name  = "Fred", Hidden = "Fred 1"});          

    dataGridView1.DataSource = backing_objects;

    this.Load += new EventHandler(Form1_Load);
    dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
}

void Form1_Load(object sender, EventArgs e)
{
    Console.WriteLine("Load");
}

void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    Console.WriteLine("Selection Changed");            
}

输出窗口显示:

Selection Changed
Selection Changed
Selection Changed
Load

请注意,您可以通过在 DataBindingComplete 事件处理程序期间附加它来使选择更改在加载事件之后触发。

dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
}

现在在输出窗口中你只能看到:

Load

在网格选择改变(例如通过单元格点击)之前,没有选择改变的输出

关于c# - DataGridView 中的 CellClick 事件和 SelectionChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883702/

相关文章:

c# - 搜索并替换具有多个属性的对象中的值......C#

winforms - 在 Visual Studio 中隐藏警告的特定实例?

ajax - 使用 Backbone.js 获取 YouTube 观看次数

asp.net - ASP.NET Gridview 控件中事件的触发顺序是什么?

c# - 正确命名 C# 事件和处理程序

C#——从 MySQL 检索数据并在 "pages"中对它们进行排序,而不使用 DataGridView

c# - ASP.Net MVC 5 OAuth2 Facebook 声明未保留。为什么?

c# - 跨 MVC Web 应用程序集中公共(public)代码的最佳方法?

winforms - 在日期时间选择器窗口窗体中设置默认时间

c# - Excel 数据到 TreeView C#