[英]DataGridView not selecting last row on load
I have a DataGridView
as part of a form that, when all of its rows are populated, should select the last row by default. 我有一个DataGridView
作为表单的一部分,当填充其所有行时,默认情况下应选择最后一行。
public MyForm()
{
InitializeComponent();
Reload();
}
private void Reload()
{
// add/populate the rows here
if(dgv.Rows.Count > 0)
{
dgv.Rows[dgv.Rows.Count - 1].Selected = true;
}
}
I have the SelectionMode
set to FullRowSelect
and MultiSelect
is false
. 我将SelectionMode
设置为FullRowSelect
并且MultiSelect
为false
。
Anyone know why this isn't working? 有人知道为什么这行不通吗? The first row is always still selected when the form pops up. 弹出表格时始终始终选择第一行。
This issue stems from the Order of Events in Windows Forms when loading a Form
. 这个问题从茎中的Windows窗体事件的顺序加载时Form
。 If you call Reload()
in the constructor of the Form
the forms controls haven't actually had a chance to load yet. 如果在Form
的构造函数中调用Reload()
,则窗体控件实际上还没有加载的机会。 Instances of them exist, but not the rendered objects. 它们的实例存在,但渲染的对象不存在。
Instead you should override one of the other form load events such as OnLoad
and call Reload()
from there. 相反,您应该覆盖其他表单加载事件之一,例如OnLoad
然后从那里调用Reload()
。 Remove the call to Reload()
from your constructor. 从构造函数中删除对Reload()
的调用。
public MyForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Reload();
}
private void Reload()
{
// add/populate the rows here
if(dgv.Rows.Count > 0)
{
dgv.Rows[dgv.Rows.Count - 1].Selected = true;
}
}
Using this method will ensure that your controls have finished loading before you start manipulating them. 使用此方法将确保控件在开始操作之前已完成加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.