2

I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9 columns) with data from text file. Code is here:

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

After that i have this:

ConvertToDataTable(filePath, 9);

This is gridview:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

How can i do that?

Nikola
  • 55
  • 1
  • 6

2 Answers2

3

Before setting the DataSource of the grid

tbl.Columns[8].SetOrdinal(0);

This will change the Ordinal property of the DataColumn inside the DataTable.DataColumnCollection in a way that the grid sees, as first column, your 9th column. Of course all other columns move up to a new index position

Steve
  • 213,761
  • 22
  • 232
  • 286
1

For further reading, it's discussed in detail here!

https://www.codeproject.com/Questions/711397/How-to-Change-order-of-columns-in-gridview

How to reorder columns in gridview dynamically

Then some add/remove column pieces with "geekwithblogs" site http://geekswithblogs.net/dotNETvinz/archive/2009/06/03/move--autogenerate-columns-at-leftmost-part-of-the-gridview.aspx

Community
  • 1
  • 1
CodeMad
  • 950
  • 2
  • 12
  • 30