我正在尝试构建一个UserControl,允许用户根据需要使用尽可能多的TextBox。
我的流程:
我的问题:
这是我的代码:
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;
}
}
}