c# - 如何更改gridview中的列顺序?

标签 c# asp.net gridview position

我想更改 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/

相关文章:

c# - 无法使用实例引用访问静态成员;用类型名称限定它

c# - EWS 读取邮件纯文本正文获取 ServiceObjectPropertyException

c# - MVC4 中的全局方法

android - 如何在 GridView 中设置图像大小

c# - GridView PageIndexChanging 不起作用

c# - 如何在表单中动态添加自定义控件

c# - MongoDB C# 单声道

asp.net - 如何使用 ASP.NET Identity 使声明无效?

asp.net - 如何管理 Azure 应用服务中的(非 SSL)证书?

asp.net - 在 GridView 中显示本地时间