C# 创建多个文本框用户控件
我正在尝试构建一个UserControl,它将允许用户根据需要创建尽可能多的文本框 我的过程: 用户看到一个+按钮 单击该按钮将在当前文本框下方添加一个新文本框 每个文本框的名称为:name\u numberOfTextBox。e、 g:第一个是文本框1,第二个是文本框2等等。。 我的问题: .Net在呈现页面时弄乱了我的名字,将myControlName添加到每个名字中。。 .Net干扰了我的ID-它为每个文本框提供了不同的ID,这使得我无法使用Page.FindControl方法来获取文本框 每次单击+按钮,它都会添加一个新的文本框,但会删除上一个文本框中已输入的内容,因为页面生命周期会再次调用。 这是我的代码:C# 创建多个文本框用户控件,c#,asp.net,controls,C#,Asp.net,Controls,我正在尝试构建一个UserControl,它将允许用户根据需要创建尽可能多的文本框 我的过程: 用户看到一个+按钮 单击该按钮将在当前文本框下方添加一个新文本框 每个文本框的名称为:name\u numberOfTextBox。e、 g:第一个是文本框1,第二个是文本框2等等。。 我的问题: .Net在呈现页面时弄乱了我的名字,将myControlName添加到每个名字中。。 .Net干扰了我的ID-它为每个文本框提供了不同的ID,这使得我无法使用Page.FindControl方法来获取文本框
如果您没有任何代码,恐怕我们无法帮助您使用代码。当你遇到问题时,试着问一下。请不要忘记发布您的代码。@nvoigt谢谢您的评论,代码已添加:
public partial class MultipleTextBox : System.Web.UI.UserControl
{
private readonly string SESSION_TEXTBOX_LIST = "textboxList";
private readonly string SESSION_NAME = "multipleTextBoxName";
private List<TextBox> textBoxList;
private string name;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnRemove.Visible = false;
Session[SESSION_TEXTBOX_LIST] = null;
Session[SESSION_NAME] = null;
textBoxList = new List<TextBox>();
Session[SESSION_TEXTBOX_LIST] = textBoxList;
return;
}
if (Session[SESSION_NAME] != null)
name = (string)Session[SESSION_NAME];
if (Session[SESSION_TEXTBOX_LIST] != null)
textBoxList = (List<TextBox>)Session[SESSION_TEXTBOX_LIST];
}
protected void btnAdd_Click(object sender, EventArgs e)
{
textBoxList.Add(createTextBox());
ShowTextboxes();
btnRemove.Visible = true;
}
protected void btnRemove_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)container.FindControl(name + "_" + textBoxList.Count);
textBoxList.Remove(textBox);
container.Controls.Remove(textBox);
}
private TextBox createTextBox()
{
TextBox textbox = new TextBox();
textbox.Attributes["name"] = name + "_" + (textBoxList.Count + 1);
textbox.Attributes["id"] = name + "_" + (textBoxList.Count + 1);
return textbox;
}
private void ShowTextboxes()
{
if (textBoxList == null || name == null)
return;
foreach (TextBox textBox in textBoxList)
{
container.Controls.Add(textBox);
container.Controls.Add(new LiteralControl("<br/>"));
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
}