views:

1343

answers:

3

I have a ASP.NET GridView that uses template columns and user controls to allow me to dynamically construct the datagrid. Now I'm implementing the event handler for inserting a row. To do that, I create an array of default values and add it to the data table which is acting as a data source. However, when my OnLoad event is fired on postback, all my template columns no longer have the user controls. My gridview ends up just being all blank with nothing in it and my button column disappears as well (which contains the add row, delete row and save buttons).

My row add event just does this:

    public void AddDataGridRow()
    {
        List<object> defRow = new List<object>();

        for (int i = 0; i < fieldNames.Count; i++)
        {
            defRow.Add(GetDefaultValueFromDBType(types[i]));   
        }

        dt.Rows.Add(defRow);
    }

It is fired from a button in a user control that's implement like this:

    protected void Button1_Click(object sender, EventArgs e)
    {
        ((Scoresheet)(this.Page)).AddDataGridRow();
    }

My on load event does a bunch of stuff on first run to set the GridView up but I don't run that again by using the IsPostBack property to tell.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Initialize();
    }

Anyone have any hints as to why my user controls are vanishing?

A: 

Do you have the EnableViewState=true on the usercontrols and the GridView?

craigmoliver
A: 

Is the AddDataGridRow() method called by Initialize()? You basically have two options:

  1. Bind the grid on every postback and do not use viewstate (performace loss)
  2. Bind the Grid only the first time (if (!IsPostBack)), and make sure that your user controls keep their viewstate.

From your code, it is not clear whether the user controls keep viewstate and what they have in them. It is not even clear what is the execution order of the methods you've shown. There is no binding logic, so even if you keep adding rows, the grid may still not be bound. Please elaborate a bit and show the whole page codebehind.

Slavo
+2  A: 

You have to add the controls to the grid on every page_load, not just if it's (!Postback)

Shawn Simon