问题
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