1
votes

I am using ASP.NET Grid View to display data from tables. I want to arrange the Columns in a specific order selected by user.

Explanation : I would like to swap columns (i.e. index 3 to becomes 5 etc) based on input from the user,is this possible?

I have tried with this code ..but still it gives unexpected result

        var boundF0 = (BoundField)GVReport.Columns[0];
        var boundF5 = (BoundField)GVReport.Columns[5];

        GVReport.Columns.RemoveAt(0);
        GVReport.Columns.RemoveAt(5);

        GVReport.Columns.Insert(0, boundF5);
        GVReport.Columns.Insert(5, boundF0); 

any idea what went wrong ?

1
I think the problem would be because you're trying to manipulate the Gridview object, rather than the data you're binding to the gridview object - Brett
could you explain what the unexpected result is? - naveen

1 Answers

0
votes

You can use http://www.devexpress.com/ for Gridview or below is code for traditional method.

DataTable dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));

while (dr.Read())
dt.Rows.Add(new object[] { dr[0], dr[1] });

Grid1.DataSource = dt;
Grid2.DataBind();

This would give you a grid with Column1 and Column2. Once you changed
the order you can do following

If (order_changed)
{
dt.Columns.Add("Column2", typeof(string));
dt.Columns.Add("Column1", typeof(string));
while (dr.Read())
dt.Rows.Add(new object[] { dr[1], dr[0] });
}

else
{

dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));
while (dr.Read())
dt.Rows.Add(new object[] { dr[0], dr[1] });
}

Now you would get a grid with Column2 and Column1

Set the autogeneratecolumns property of grid to true and you will get the columns