我想更改 gridview 列的顺序(第 8 个为第一个,第一个为第二个,第二个为第三个......)。我正在用文本文件中的数据填充我的 gridview(有 9 列)。代码在这里:
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = File.ReadAllLines(filePath);
List<string> ekran = new List<string>();
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < 9; cIndex++)
{
if (cols[cIndex].Contains('_'))
{
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
else
{
cols[cIndex] += '_';
cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
dr[cIndex] = cols[cIndex];
}
}
for (int cIndex = 0; cIndex < 9;cIndex++ )
if (dr[cIndex].ToString() == promenljiva)
tbl.Rows.Add(dr);
}
this.GridView1.DataSource = tbl;
this.GridView1.DataBind();
return tbl;
}
之后我有这个:
ConvertToDataTable(filePath, 9);
这是 GridView :
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
我怎样才能做到这一点?
最佳答案
设置网格的数据源之前
tbl.Columns[8].SetOrdinal(0);
这将更改 Ordinal DataTable.DataColumnCollection 内的 DataColumn 属性,网格将其视为第一列,即第九列。当然,所有其他列都会向上移动到新的索引位置
关于c# - 如何更改gridview中的列顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144149/