datagrid中复选框列的索引错误 [英] wrong index of checkbox column in datagrid
问题描述
我有这段代码在第三个位置添加一个复选框列,但是此列的索引(bloqueador)为0而不是3.这是怎么回事?
I have this code to add a checkbox column in the third position, but the index of this column(bloqueador) is 0 and not 3. What is wrong?
public void bloqselect()
{
DataGridViewCheckBoxColumn chkSelect = new DataGridViewCheckBoxColumn();
chkSelect.Selected = false;
chkSelect.HeaderText = "Bloqueador";
chkSelect.Name = "chkSelect";
grid_lic.Columns.Insert(3, chkSelect);
if (chkSelect.Selected == true)
bloqueador = 1;
else
bloqueador = 0;
}
推荐答案
这是每个人都以艰难的方式学习到的列的加载顺序的古怪之处.当您将数据绑定到DataGridView时, 会在Form构造函数运行完毕后-始终解析列及其索引.对于手动添加的列,情况并非如此-它们会立即解决.
It's a quirk about the loading order of the columns everyone learns the hard way. When you bind data to your DataGridView, the columns and their indices are resolved after the Form constructor has finished running - always. This is not true for manually added columns - they are resolved immediately.
为什么这么重要?假设您有一个数据源,它将解析为 Foo
, Bar
和 Baz
列.然后,将列 Add
插入位置2.这样做的代码如下:
Why does that matter? Let's say you have a DataSource that will resolve into the columns Foo
, Bar
, and Baz
. Then you insert column Add
into position 2. Your code to do so may look like:
dataGridView.DataSource = GetFooBarBazSource();
dataGridView.Columns.Insert(2, theAddColumn);
列索引将直接取决于何时运行此代码-在Form构造函数中还是之后(例如,在 Form.Load
中说):
The column indices will depend directly on when you ran this code - in the Form constructor or after (let's say in Form.Load
):
╔═════╦═════╦═════╦═════╗
║ Foo ║ Bar ║ Add ║ Baz ║
╠═════╬═════╬═════╬═════╣
Form Constructor ║ 1 ║ 2 ║ 0 ║ 3 ║
Form_Load() ║ 0 ║ 1 ║ 2 ║ 3 ║
╚═════╩═════╩═════╩═════╝
如果您希望按预期的那样固定索引顺序,只需为 Form.Load
或 grid_lic.DataBindingComplete
添加事件处理程序,然后调用该处理程序中的 bloqselect()
.
If you want to fix the index order to be as expected, simply add an event handler for either Form.Load
or grid_lic.DataBindingComplete
, then make your call to bloqselect()
within that handler.
这篇关于datagrid中复选框列的索引错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!