0

I am creating controls base on the number of rows in my data table. Here is my code:

 for (int i = 0; i < dataTable1.Rows.Count; i++)
                    {
                        TableRow tr = new TableRow();

                        TableCell td1 = new TableCell();
                        TableCell td2 = new TableCell();
                        td1.Style.Add("width", "200px");

                        Label lblSite = new Label();
                        lblSite.ID = "lblSite";
                        lblSite.Text = dt.Rows[i]["Title"].ToString();


                        TextBox txtComment = new TextBox();
                        txtComment.ID = "txtComment";
                        txtComment.TextMode = TextBoxMode.MultiLine;

                        td1.Controls.Add(lblSite);
                        td2.Controls.Add(txtComment);

                        tr.Cells.Add(td1);
                        tr.Cells.Add(td2);

                        Table1.Rows.Add(tr);
                        Table1.EnableViewState = true;
                        ViewState["Table1"] = true;
                    }

Now i want to get both the control in button click event and their text one by one.

Thanks.

1 Answer 1

0

Dynamically created controls will not be part of the page view state and hence during PostBack those controls will get lost. To avoid this, you should handle Page_Load event and recreate those controls dynamically.

Below is a pseudo code you can follow

protected void Page_Load(object sender, EventArgs e)
{
    Label l = new Label();
    l.ID = "lblTest";
    l.Text = "Some Text";

    Page.Controls.Add(l);
}

Now in button click event you can find the control

Label l = Page.FindControl("lblTest");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.