[英]Dynamically create text inputs (ASP.net/C#)
I have an input field on my page where the user will type in the number of text inputs they want to create. 我的页面上有一个输入字段,用户将在其中键入要创建的文本输入的数量。 The action for the button is: 按钮的操作是:
int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
}
Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. 现在,我有另一个按钮,用户在填写所有动态创建的文本框后会单击该按钮。 Questions, first of all, am I creating the text boxes dynamically in the correct place? 问题,首先,我是否在正确的位置动态创建文本框? How would I get the values out of the dynamically-created text boxes? 如何从动态创建的文本框中获取值? (The dynamically-created text boxes are being added to the Panel "answer_inputs". (动态创建的文本框正被添加到Panel“answer_inputs”中。
When creating web controls dynamically, I find it best to have the controls themselves report in the answers. 在动态创建Web控件时,我发现最好让控件本身在答案中报告。 You can achieve it like this: 你可以这样做:
Create something in your Page class to store the values: 在您的Page类中创建一些内容来存储值:
private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();
Make a method to act as a callback for the textboxes when their value changes: 创建一个方法,在其值发生变化时充当文本框的回调:
void tmp_TextChanged(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
if(txt!=null)
{
values.Add(txt,txt.Text);
}
}
And then add this method to each textbox as they are added: 然后在添加时将此方法添加到每个文本框中:
int num_flds;
if(!int.TryParse(a_fld.Text,out num_flds))
{
num_flds = 0;
}
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
tmp.TextChanged += tmp_TextChanged;
}
Finally, you iterate through the dictionary on callback to see if it holds any values. 最后,在回调中迭代字典以查看它是否包含任何值。 Do this in the OnPreRender method for instance. 例如,在OnPreRender方法中执行此操作。
Edit: There is a problem with this, if the number of text fields are decreased on postback. 编辑:如果在回发时减少文本字段的数量,则存在此问题。 Some safe way to recreate the previous textfields on postback should be employed. 应该采用一些在回发时重新创建先前文本字段的安全方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.