リストビューで行きましょう
<asp:ListView ID="lvDynamicTextboxes" runat="server"
ItemPlaceholderID="itemPlaceholder"> <LayoutTemplate> <table> <asp:PlaceHolder ID="itemPlaceholder"
runat="server"></asp:PlaceHolder> </table> </LayoutTemplate> <ItemTemplate> <tr> <asp:TextBox ID="txtText" runat="server"> </asp:TextBox> </tr> </ItemTemplate>
</asp:ListView>
<asp:Button ID="btnAddTextBox" runat="server"
Text="Add" onclick="btnAddTextBox_Click" />
そしていくつかのコード
private void BindListView()
{
//get the current textbox count int count = 1;
if (ViewState["textboxCount"] != null)
count = (int)ViewState["textboxCount"];
//create an enumerable range based on the current count IEnumerable<int> enumerable = Enumerable.Range(1, count);
//bind the listview this.lvDynamicTextboxes.DataSource = enumerable;
this.lvDynamicTextboxes.DataBind();
}
private void IncrementTextboxCount()
{
int count = 1;
if (ViewState["textboxCount"] != null)
count = (int)ViewState["textboxCount"];
count++;
ViewState["textboxCount"] = count;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindListView();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
this.IncrementTextboxCount();
this.BindListView();
}
これらの追加されたテキストボックスから値を抽出するには:
private IList<string> GetValues()
{
List<string> values = new List<string>();
TextBox txt = null;
foreach (ListViewItem item in this.lvDynamicTextboxes.Items)
{
if (item is ListViewDataItem)
{
txt = (TextBox)item.FindControl("txtText");
values.Add(txt.Text);
}
}
return values;
}