4

I created a web page and I used to add server side controls to table dynamically.

I assigned them individually the id's.. But I am unable to access these dynamically created server controls.

C# code:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            int num_row = (int)Session["No_of_Rows"];
            for (int i = 2; i < num_row; i++)
            {
                TableRow row = new TableRow();
                TableCell cell1 = new TableCell();
                TableCell cell2 = new TableCell();
                TextBox tb = new TextBox();
                CheckBox cb = new CheckBox();

                row.ID = "rw" + i;

                cell1.ID = "c" + i + "1";
                cell2.ID = "c" + i + "2";

                tb.ID = "txt" + i;
                tb.EnableViewState = true;
                cb.ID = "chk" + i;

                cell1.Controls.Add(cb);
                cell2.Controls.Add(tb);

                row.Cells.Add(cell1);
                row.Cells.Add(cell2);

                tbl.Rows.Add(row);
            }
        }
        else
        {
            Session["No_of_Rows"] = 2;
        }




    }
    protected void addRow(object sender, EventArgs e)
    {

        int num_row = (int)Session["No_of_Rows"] + 1;
        TableRow row = new TableRow();
        TableCell cell1 = new TableCell();
        TableCell cell2 = new TableCell();
        TextBox tb = new TextBox();
        CheckBox cb = new CheckBox();

        row.ID = "rw" + num_row;

        cell1.ID = "c" + num_row + "1";
        cell2.ID = "c" + num_row + "2";

        tb.ID = "txt" + num_row;
        //tb.EnableViewState = true;
        cb.ID = "chk" + num_row;

        cell1.Controls.Add(cb);
        cell2.Controls.Add(tb);

        row.Cells.Add(cell1);
        row.Cells.Add(cell2);

        tbl.Rows.Add(row);
        Session["No_of_Rows"] = tbl.Rows.Count;



    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();

        int num_row = Convert.ToInt16(tbl.Rows.Count);
        for (int i = 1; i < num_row; i++)
        {
            string tstr = "txt" + i;
            tb = (TextBox)this.FindControl(tstr);

        }
        Label1.Text = tb.Text;
    }

asp code:

    <form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" Text="textbox value is"></asp:Label>
    <asp:Table ID="tbl" runat="server">
        <asp:TableRow ID="rw0">
            <asp:TableCell ID="c01" Width="100px">
                <asp:CheckBox runat="server" ID="chk0" />
            </asp:TableCell>
            <asp:TableCell ID="c02" Width="100px">
                <asp:TextBox runat="server" ID="txt0" />
            </asp:TableCell></asp:TableRow>
        <asp:TableRow ID="rw1">
            <asp:TableCell ID="c11" Width="100px">
                <asp:CheckBox ID="chk1" runat="server" />
            </asp:TableCell>
            <asp:TableCell ID="c12" Width="100px">
                <asp:TextBox runat="server" ID="txt1" />
            </asp:TableCell></asp:TableRow>
    </asp:Table>
    <asp:Button ID="btn1" runat="server" Text="Add Row" OnClick="addRow" />
</div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
</form>

Please assist me in this.

5
  • Hi Alwyn, can you pls let me know where exactly do you have the above code? i mean in which event or in which method? Commented Oct 28, 2013 at 13:44
  • Hi Saranya I have edited the code for better clarity. Commented Oct 28, 2013 at 14:14
  • I have posted a answer at the bottom. pls check. Commented Oct 28, 2013 at 14:30
  • 1
    The reason you are not getting any values in label1 is , your logic is such that only the last accessed textbox value is shown in the label. for some reason the view state of the last text box created dynamically is not maintained :( and your label value is null Commented Oct 28, 2013 at 14:39
  • 1
    found the error. problem was with logic. int num_row = (int)Session["No_of_Rows"] + 1; remove the +1 and it works..Also your logic is such that only the value of the last text box is displayed in the label. Use a stringbuilder and append it inside loop to have values of all. Commented Oct 28, 2013 at 15:19

4 Answers 4

2

To test your scenario, i added 2 controls txtOutput and Getvalues button.Everything seems to be fine, except your control ids starts from 0 where as your for loop starts from 1.

However this should not return null in FindControl.

I suspect your table id is incorrect because in the other post you referred the table id is "tbl".

Other wise everything seems to be correct. Anyway, i have pasted your code which i tried here, and it works.

Another possibility where you will get the error is if u try to access the controls before even they are created in Page_Load. However because you have 2 rows static in your table, your code should work irrespective of the dynamic control creation. Pls try the below code and update

<form id="form1" runat="server">
        <div>
        <div>
        <asp:Table ID="tbl" runat="server">
            <asp:TableRow ID="rw0">
                <asp:TableCell ID="c01" Width="100px">
                    <asp:CheckBox runat="server" ID="chk0" />
                </asp:TableCell>
                <asp:TableCell ID="c02" Width="100px">
                    <asp:TextBox runat="server" ID="txt0" />
                </asp:TableCell></asp:TableRow>
            <asp:TableRow ID="rw1">
                <asp:TableCell ID="c11" Width="100px">
                    <asp:CheckBox ID="chk1" runat="server" />
                </asp:TableCell><asp:TableCell ID="c12" Width="100px">
                    <asp:TextBox runat="server" ID="txt1" />
                </asp:TableCell></asp:TableRow>
        </asp:Table>
        <asp:textbox runat="server" id="checkIn" ClientIDMode="Static" name="checkIn" ></asp:textbox>
        <asp:Button ID="btn1" runat="server" Text="Add Row" OnClick="addRow" />
        <br />
        <asp:Button ID="GetValues" runat="server" Text="GetValues" OnClick="GetValuesfromDynamicControls" />
        <asp:TextBox ID="txtOutput" runat="server" />

//code behind starts here

 public partial class DynamicControl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack)
            {
                int num_row = (int)Session["No_of_Rows"];
                for (int i = 2; i < num_row; i++)
                {
                    TableRow row = new TableRow();
                    TableCell cell1 = new TableCell();
                    TableCell cell2 = new TableCell();
                    TextBox tb = new TextBox();
                    CheckBox cb = new CheckBox();

                    row.ID = "rw" + i;

                    cell1.ID = "c" + i + "1";
                    cell2.ID = "c" + i + "2";

                    tb.ID = "txt" + i;
                    tb.EnableViewState = true;
                    cb.ID = "chk" + i;

                    cell1.Controls.Add(cb);
                    cell2.Controls.Add(tb);

                    row.Cells.Add(cell1);
                    row.Cells.Add(cell2);

                    tbl.Rows.Add(row);
                }
            }
            else
            {
                Session["No_of_Rows"] = 2;
            }
        }

        protected void addRow(object sender, EventArgs e)
        {
            int num_row = (int)Session["No_of_Rows"];
            TableRow row = new TableRow();
            TableCell cell1 = new TableCell();
            TableCell cell2 = new TableCell();
            TextBox tb = new TextBox();
            CheckBox cb = new CheckBox();

            row.ID = "rw" + num_row;

            cell1.ID = "c" + num_row + "1";
            cell2.ID = "c" + num_row + "2";

            tb.ID = "txt" + num_row;
            tb.EnableViewState = true;
            cb.ID = "chk" + num_row;

            cell1.Controls.Add(cb);
            cell2.Controls.Add(tb);

            row.Cells.Add(cell1);
            row.Cells.Add(cell2);

            tbl.Rows.Add(row);
            Session["No_of_Rows"] = tbl.Rows.Count;
        }


        protected void GetValuesfromDynamicControls(object sender, EventArgs e)
        {
            //int rows =Convert.ToInt32( Session["No_of_Rows"]);
            int rows = Convert.ToInt32(tbl.Rows.Count);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; i++)
            {               
                    TextBox tb =(TextBox) Page.FindControl("txt" + i);
                    sb.Append(tb.Text + ";");                
            }

            txtOutput.Text = sb.ToString();
        }

    }
Sign up to request clarification or add additional context in comments.

2 Comments

You have solved two of my great problems. So I want to give you dairy milk silk B-) .. Let me know if you would like to re imburse it :)
Just for information: The code given by you works independently. But it doesnt work if I incorporate it to the application code. Later I realised its because of master page. And thats why i was getting null. For that we need to give tb = (TextBox)sometable.FindControl("txt" + i);
2

On Each Post Back, Dynamically Created controls may not visible. So You need to recreate dynamic Controls on each post back.Then you can access these controls.

3 Comments

I have done this step Priya. But I am unable to access it. This is how I done stackoverflow.com/questions/19562117/…
then You are doing something wrong somewhere, Dynamic Controls are working this way, Every time on post back, On Page-Load Event, You need to recreate your dynamic controls with the same IDS, with which your were created. suppose at first time, you are creating one textbox (with ID txt1) and one dropdown control (with ID drp1), then if You click on dropdown, means POSTBACK occurs, then Page-Load Event, You need to recreate txtbox and dropdown comntrol with same IDs: txt1 and drp1 ,Only then You can access these controls further.
I have performed the same. Under page load event, I have re created all the conrols using the for loop. and in add row button event I have added the new row. Yes I am missing some where. wait I will post the whole code so that you could figure it out if you have free time :). Thanks a lot.
2

TRY:

            tb = (TextBox)sometable.FindControl("txt" + i);

3 Comments

wow PJM. This is really a usefull one if we have masterpages. Thanks a lot buddy. But if we dont have masterpage then we can directly use this.control or page.control as told by Saranya above
FindControl() will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls, that is why you need to specify the naming container, table.
Answer to this question should be as simple and concise as this one.
1

you can do that like this :

TextBox txt= (TextBox)FindControl("txt"+i.Tostring());
string txtValue=txt.Text;

and to access all of the textboxes in a for loop :

int num_row = Convert.ToInt16(sometable.Rows.Count);
for (int i = 1; i < num_row; i++)
{
    string txtID="txt" + i.Tostring();
    TextBox txt= (TextBox)FindControl(txtID);
    string txtValue=txt.Text;
}

8 Comments

@ChrisFarmer he has not converted i to string though he is not getting the right Id of the Textbox when he does : FindControl("txt" + i);
I don't think that's true. The conversion happens automatically with the +. stackoverflow.com/questions/751303/…
he Karam : actually the i am getting the correct id. I put breakpoint and checked. Howeved I did as you said. still the result is same.
@AlwynMiranda where have you declared tb ? and where are you calling tb ? note you are assigning to tb multiple times in the for and you are calling tb.Text after the for loop !
tb is declared before the block as : TextBox tb = new TextBox();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.