我是如何从文本框ASP.NET中正确获取值的 [英] How I get the values properly from textboxes ASP.NET
问题描述
我在Aspx上有一个for循环和面板;
I have a for loop and panel on Aspx;
<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>
它返回7个texboxes,我可以使用以下代码从texbox中获取值;
It returns 7 texboxes and i can get values from texboxes with following code;
int j = 0;
foreach (TextBox tbValue in Panel1.Controls.OfType<TextBox>())
{
xArray[j] = tbValue.Text;
j++;
}
例如;我在html上填充texbox
tb1.text:Sample1
tb2.text:Sample2
tb3 .text:Sample3
tb4.text:null
tb5.text:null
tb6.text:null
当我发布它时,tb.text返回一个值为Sample1,Sample2,Sample3 ,,,
所以,
xArray [0] =Sample1,Sample2,Sample3 ,,,
xArray [1] = null
xarray [2] = null
。
。
。
应该是;
xArray [0] = Sample1
xArray [1] = Sample2
...
如何正确填写?
我尝试过:
没有................... ....
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.......................
推荐答案
它不能与Asp TextBox一起使用,尝试使用HTML输入元素
< big> ASPX
It wont work with Asp TextBox, try using HTML input element
ASPX
<%for (int i = 0; i <= 6; i++)
{%>
<input type="text" name="txt_<%= i %>" />
<%} %>
代码背后
Code Behind
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;
}
}
嘿伙计,
你注意到了吗所有动态生成的文本框都具有相同的ID?理想情况下,Web表单中的所有控件都应具有唯一ID。如果你试图从aspx页面动态分配唯一的id,那么它就不会发生。
我的建议:
1.)从aspx页面删除此代码:
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:
<%for (int i = 0; i <= 6; i++)
{%>
<asp:TextBox ID="tb" class="form-control" runat="server"></asp:TextBox>
<%} %>
2.)在您的代码中添加以下代码:
2.) Add below code in your code behind:
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,现在可行。
Voila , Now this works.
这篇关于我是如何从文本框ASP.NET中正确获取值的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!