Swapping columns in a DataGrid

T

Tim

Hi,

The DataGrid.Bind() below works fine as is. Now, I want to swap the
1st and 2nd columns of the DataGrid (see the commented out section):

DataSet ds = new DataSet();
ds.Tables.Add(this.GetTable(dr));
DataGrid1.DataSource = ds.Tables[0];

//DataGridColumn dgCol1;
//DataGridColumn dgCol2;
//int tryme = Convert.ToInt32(DataGrid1.Columns.Count);
//Response.Write(tryme); //returns zero
//dgCol1 = DataGrid1.Columns[0];
//dgCol2 = DataGrid1.Columns[1];
//DataGrid1.Columns.AddAt(0,dgCol2);
//DataGrid1.Columns.AddAt(1,dgCol1);

DataGrid1.DataBind();

However, DataGrid1.Columns.Count returns zero. How come? A DataGrid
with 8 columns is displayed normally.

Thanks!
 
S

Scott Mitchell [MVP]

Tim said:
//DataGridColumn dgCol1;
//DataGridColumn dgCol2;
//int tryme = Convert.ToInt32(DataGrid1.Columns.Count);
//Response.Write(tryme); //returns zero
//dgCol1 = DataGrid1.Columns[0];
//dgCol2 = DataGrid1.Columns[1];
//DataGrid1.Columns.AddAt(0,dgCol2);
//DataGrid1.Columns.AddAt(1,dgCol1);

DataGrid1.DataBind();

However, DataGrid1.Columns.Count returns zero. How come? A DataGrid
with 8 columns is displayed normally.

Tim, the problem you are having is because the DataGrid's Columns
collection is not build up until *after* the data is bound to the grid
(that is, after the call to the DataBind() method).

Why can't you just reorder the BoundColumns in the <Columns> section, or
(if you're using AutoGenerateColumns=False), why can't you just
reorder the fields in your SQL query?

--

Scott Mitchell
(e-mail address removed)
http://www.4GuysFromRolla.com
http://www.ASPFAQs.com
http://www.ASPMessageboard.com

* When you think ASP, think 4GuysFromRolla.com!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top