2

I'm facing a very common issue and I've tried almost every solution but none of them solved my problem. I've created a Grid View and I want it to have dynamic columns. Four columns among them must have some controls(textbox,label and checkbox) so I've created it as Template Fields(below code)

       TemplateField tf4 = new TemplateField();
        tf4.HeaderText = "Sr.No";
        CustomerBillingGrid.Columns.Add(tf4);

        TemplateField tf1 = new TemplateField();
        tf1.HeaderText = "Select";
        CustomerBillingGrid.Columns.Add(tf1);

        TemplateField tf2 = new TemplateField();
        tf2.HeaderText = "Misc";
        CustomerBillingGrid.Columns.Add(tf2);

        TemplateField tf3 = new TemplateField();
        tf3.HeaderText = "Total";
        CustomerBillingGrid.Columns.Add(tf3);

Then I've created Bound fields that displays database query result (below code)

 if (ds.Tables[0].Rows.Count > 0)
        {
            int num = 2;
            foreach (DataColumn col in ds.Tables[0].Columns)
            {
                BoundField bf = new BoundField();
                bf.HeaderText = col.ColumnName;
                bf.DataField = col.ColumnName;
                CustomerBillingGrid.Columns.Insert(num, bf);
                num++;
            }

            CustomerBillingGrid.DataSource = ds;
            CustomerBillingGrid.DataBind();

        }

After than I've Dynamically generated controls for GridView.

 protected void GenrateDynamicControls()
    {
        Label lblSNo = new Label();
        lblSNo.ID = "lblSNo";
        lblSNo.Text = "1";
        Page.Form.Controls.Add(lblSNo);

        CheckBox chkSelect = new CheckBox();
        chkSelect.ID = "chkSelect";
        chkSelect.AutoPostBack = true;
        Page.Form.Controls.Add(chkSelect);

        TextBox txtMisc = new TextBox();
        txtMisc.ID = "txtMisc";
        Page.Form.Controls.Add(txtMisc);

        TextBox txtTotal = new TextBox();
        txtTotal.ID = "txtTotal";
        Page.Form.Controls.Add(txtTotal);

    }

I've called this method on every Postback

 if (!IsPostBack)
        {


            if (!Convert.ToBoolean(ViewState["DynamicControlsGenrated"]))
            {
                GenrateDynamicControls();
            }

        }

The problem I'm facing is that all these dynamic controls gets lost every postback and the second problem is that how to add those dynamically generated controls inside GridView and keep it persistence.

Thanks,

Rohit Singh
  • 75
  • 3
  • 16

1 Answers1

0

In the case of dynamic control creation inside the grid view, you need to recreate the controls each time on postback and make sure to disable view state mode in grid view.

ViewStateMode="Disabled"