简体   繁体   中英

Set postion of gridview column with autogenerated column

I have a Gridview with autogenerated Column = "true" Now I want to change the postion of gridview column in the gridview's OnRowCreated event.

I use this code

  TableCell cell = e.Row.Cells[1];
  TableCell cell1 = e.Row.Cells[0];
  e.Row.Cells.RemoveAt(1);
  e.Row.Cells.RemoveAt(0);
  e.Row.Cells.Add(cell1);
  e.Row.Cells.Add(cell);

It works fine it moves column 0 and 1 to last positions of grid view

Now I want to move 3rd column of gridview to the first position, so I use

TableCell cell2 = e.Row.Cells[3];
e.Row.Cells.RemoveAt(3);
e.Row.Cells.AddAt(0, cell2);

but it's not working....

If you are binding the GridView to a DataTable , you could move the columns on the DataTable before you bind it to the GridView :

DataTable table = new DataTable();
table.Columns.Add("x");
table.Columns.Add("y");
table.Columns.Add("z");

table.Rows.Add("1", "2", "3");
table.Rows.Add("1", "2", "3");
table.Rows.Add("1", "2", "3");

//Move the column 
table.Columns["z"].SetOrdinal(0);

string value = table.Rows[0][0].ToString();
//Outputs 3

gridView.DataSource = table;
gridView.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM