gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:59 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com