Swapping columns in a DataGrid

Discussion in 'ASP .Net Datagrid Control' started by Tim, Apr 16, 2004.

  1. Tim

    Tim Guest

    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!
     
    Tim, Apr 16, 2004
    #1
    1. Advertisements

  2. 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

    http://www.4GuysFromRolla.com
    http://www.ASPFAQs.com
    http://www.ASPMessageboard.com

    * When you think ASP, think 4GuysFromRolla.com!
     
    Scott Mitchell [MVP], Apr 16, 2004
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.