使用自动生成的列设置GridView列的位置。

3

我有一个带有自动生成列Column = "true"Gridview,现在我想在GridviewOnRowCreated事件中更改列的位置。

我使用以下代码:

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

它可以正常工作,将列0和1移动到网格视图的最后位置。

现在我想将GridView的第三列移动到第一列位置,所以我使用:

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

但是它没有起作用...

你是如何将数据绑定到GridView上的?绑定到哪里了? - Mateus Schneiders
我使用存储过程在按钮点击时绑定网格视图 - Neha
使用哪种数据结构?Datatable? - Mateus Schneiders
你不能在将数据绑定到 GridView 之前更改 DataTable 中列的顺序吗? - Mateus Schneiders
好的,我试一下... dt.Columns["BookCode"].SetOrdinal(0); 它有效了,谢谢。 - Neha
1个回答

0

如果您将GridView绑定到DataTable,您可以在将其绑定到GridView之前移动DataTable上的列:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接