开发者

asp.net : grid view : arrange column

开发者 https://www.devze.com 2023-03-11 21:33 出处:网络
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.

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);
        GVRep开发者_运维技巧ort.Columns.Insert(5, boundF0); 

any idea what went wrong ?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消