views:

23

answers:

0

I have a GridView that has several dynamic columns (I do not know how many at design time and it could be 0-12 columns, hence need for dynamic columns). I have the columns in the grid and data bound to them - works great. There are other standard, design-time TemplateField columns with TextBox controls in them. These are bound with values that the user can edit. The grid is posted back via a Submit button.

My question is "Why does gv.Columns.Insert() cause all my TextBox data to be null on Postback, but gv.Columns.Add() works like a champ?"

Relevant SO Link

    protected void BuildColumns()
    {
    // The first column to begin to insert the columns in the GridView
    int columnIndex = 5;

    BoundField aoColumn = new BoundField();
    aoColumn.HeaderText = "New Column 1";
    gvMyGrid.Columns.Insert(columnIndex, aoColumn); // kills txtQuantity.Text on postback
    gvMyGrid.Columns.Add(aoColumn);                 // works fine
    columnIndex++;

    foreach (MyEntity my in _myEntityCollection)
    {
        BoundField myColumn = new BoundField();
        myColumn.HeaderText = String.Format("{0:d}", my.StartDate);
        gvMyGrid.Columns.Insert(columnIndex, myColumn);
        columnIndex++;
    }
}

I then go on to assign values to these BoundFields in the _RowDataBound method and all of this works great. However, when I post back and try to reference some TextBox and they are all null. And yes, I have the BuildColumns() call wrapped in if (!IsPostBack) on Page_Load.

Of course I would like to use .Insert() so that the columns can go in the proper location and not at the end of the Columns array.