简体   繁体   中英

Dynamic Controls gets lost durig Postback inside GridView in asp.net C#

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,

在网格视图内创建动态控件的情况下,您需要在每次回发时重新创建控件,并确保在网格视图中禁用视图状态模式。

ViewStateMode="Disabled"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM