How can I chance gridview column order dynamically?

  • Thread starter Thread starter Savvoulidis Iordanis
  • Start date Start date
S

Savvoulidis Iordanis

There is no column property about the position of the column in the grid. How
can I change it in code? (move the column left or right)
 
What I want to accomplish is:
I have custom gridview control that suppresses repeating values in records,
starting from the leftmost column. It calls a user SP to get the result set.
The repeating values suppression is done OK for a certain ORDER BY clause.
If I call the SP with another parameter, another ORDER BY is used. But The
gridview is always the same. I want the 2nd gridview column now, to become
first, so the repeating values suppression, is displayed OK. And this must be
done in code.
But how?
 
What I want to accomplish is:
I have custom gridview control that suppresses repeating values in records,
starting from the leftmost column. It calls a user SP to get the result set.
The repeating values suppression is done OK  for a certain ORDER BY clause.
If I call the SP with another parameter, another ORDER BY is used. But The
gridview is always the same. I want the 2nd gridview column now, to become
first, so the repeating values suppression, is displayed OK. And this must be
done in code.
But how?

what is the value of AutoGenerateColumns?
 
FALSE. Why does it matter?

Because if GridView.AutoGenerateColumns is set to true you can change
the order of the columns in the datasource. If AutoGenerateColumns is
false, you can change your columns when you build and bind the grid
from the code. For example,

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

Is it what you want?
 
Well, actully I don't like creating the column in code. I prefer to have the
columns built by the IDE. In fact I don't really like datasource controls. I
use them only to build the column in the gridview automatically and then I
delete them. Then I just change the formating of the columns (header text,
CSS, colors, heights, etc).

Is there any way to swap the generated columns, or ldelete the one first and
then insert it in another position? Or even better, just swap the header text
and the datafield/dataformat string of the columns?
 
Back
Top