T.S.
T.S.

Reputation: 19330

Column order does not hold in the DataGridView

I am adding columns in this order

var tblCol = new DataGridViewTextBoxColumn();
tblCol.HeaderText = "Table Name";
tblCol.ReadOnly = true;
tblCol.Width = 300;
tblCol.DataPropertyName = "TableName";

grdTableSelect.Columns.Add(tblCol);

var boolCol = new DataGridViewCheckBoxColumn();
boolCol.HeaderText = "Insert";
boolCol.ReadOnly = false;
boolCol.Width = 50;
boolCol.DataPropertyName = "Insert";

grdTableSelect.Columns.Add(boolCol);

boolCol = new DataGridViewCheckBoxColumn();
boolCol.HeaderText = "Update";
boolCol.ReadOnly = false;
boolCol.Width = 50;
boolCol.DataPropertyName = "Update";

grdTableSelect.Columns.Add(boolCol);

boolCol = new DataGridViewCheckBoxColumn();
boolCol.HeaderText = "Delete";
boolCol.ReadOnly = false;
boolCol.Width = 50;
boolCol.DataPropertyName = "Delete";

grdTableSelect.Columns.Add(boolCol);

tblCol = new DataGridViewTextBoxColumn();
tblCol.HeaderText = "Status";
tblCol.ReadOnly = true;
tblCol.Width = 250;
tblCol.DataPropertyName = "Status";

grdTableSelect.Columns.Add(tblCol);

Item Model

private class TableGridItem
{


    public string TableName { get; set; }

    public string Status { get; set; }

    public bool? Insert {get; set;}
    
    public bool? Delete {get; set;}
    
    public bool? Update {get; set;}
    
}

But the Status column for some reason ends up #3 prepositionally

enter image description here

I need status to be #4. Additionally - prior to today, without Status column and property in the item model, it worked as desired.

Upvotes: 0

Views: 97

Answers (1)

JohnG
JohnG

Reputation: 9469

If you set the data source and let the grid auto generate the columns, it may give a hint as to why this is happening. In addition, if the DisplayIndex of the column is something greater than the total number of columns, then obviously something may not work.

Example, if you set the first columns DispalyIndex to 4, THEN "add" the column to the grid, then obviously there is no “index” 4. Therefore, instead of setting the DisplayIndex when you create the columns… Set the DisplayIndex “after” all the columns have been added and the data source has been set.… Something like…

  grdTableSelect.Columns[0].DisplayIndex = 0;
  grdTableSelect.Columns[1].DisplayIndex = 4;
  grdTableSelect.Columns[2].DisplayIndex = 2;
  grdTableSelect.Columns[3].DisplayIndex = 3;
  grdTableSelect.Columns[4].DisplayIndex = 1;

Or you could simply change the order of the properties in the TableGridItem class… something like…

public class TableGridItem {

  public string TableName { get; set; }

  public bool? Insert { get; set; }

  public bool? Delete { get; set; }

  public bool? Update { get; set; }

  public string Status { get; set; }
}

Upvotes: 1

Related Questions