Click here to Skip to main content
15,907,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a for loop and panel on Aspx;

C#
<asp:Panel ID="Panel1" runat="server">

         <%for (int i = 0; i <= 6; i++)
          {%>
<asp:TextBox ID="tb" class="form-control"  runat="server"></asp:TextBox>

         <%} %>
   </asp:Panel>


It returns 7 texboxes and i can get values from texboxes with following code;

C#
 int j = 0;
        foreach (TextBox tbValue in Panel1.Controls.OfType<TextBox>())
        {
            xArray[j] = tbValue.Text;
j++;
        }


for example; i'm filling texboxes on html

tb1.text: Sample1
tb2.text: Sample2
tb3.text: Sample3
tb4.text: null
tb5.text: null
tb6.text: null

When i post it, tb.text returned one value as "Sample1,Sample2,Sample3,,,,"
So,
xArray[0]="Sample1,Sample2,Sample3,,,,"
xArray[1]=null
xarray[2]=null
.
.
.
It should be;
xArray[0]=Sample1
xArray[1]=Sample2
...
How can i fill properly?

What I have tried:

nothing.......................
Posted
Updated 19-Aug-16 19:29pm
v4

It wont work with Asp TextBox, try using HTML input element

ASPX

HTML
    <%for (int i = 0; i <= 6; i++)
             {%>
           <input type="text" name="txt_<%= i %>"  />

<%} %>

Code Behind
C#
protected void Button1_Click(object sender, EventArgs e)
     {
         string[]xArray =new string[7];

         for (int i = 0; i <= 6; i++)
         {
             string value = Request.Form.Get("txt_" + i);
             xArray[i] = value;
         }


     }
 
Share this answer
 
Hey Buddy,
Did you notice that all your dynamically produced textboxes have the same id ? Ideally all controls in a web form should have unique id. If you try to assign unique id dynamically from aspx page, then it's not going to happen.
My suggestions:
1.) Remove this code from aspx page:
ASP.NET
 <%for (int i = 0; i <= 6; i++)
          {%>
<asp:TextBox ID="tb" class="form-control"  runat="server"></asp:TextBox>
 
         <%} %>


2.) Add below code in your code behind:
C#
for (int i = 0; i <= 6; i++)
           {
               TextBox tb = new TextBox();
               tb.ID = "tb" + i.ToString();
               tb.Attributes.Add("class", "form-control");
               Panel1.Controls.Add(tb);
           }


Voila , Now this works.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900