wrong index of checkbox column in datagrid

醉酒当歌 提交于 2021-01-29 03:09:24

问题


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;
}

checkbox column index


回答1:


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.

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);

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   ║
                 ╚═════╩═════╩═════╩═════╝

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.



来源:https://stackoverflow.com/questions/34386411/wrong-index-of-checkbox-column-in-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!