【发布时间】:2011-07-02 03:45:03
【问题描述】:
我有一个问题困扰了我三天。
在我的网络表单上,我想有一个按钮,点击它我想在 asp:PlaceHolder 中动态创建五个文本框。
我希望,即使在 postBack 之后,我在这个 texBoxes 中输入的值也会被保存。使用第二个按钮,我想存储它们。
我已经阅读了有关页面生命周期、viewState、IsPostBack 的文章...很多动态创建控件的文章,但我仍然无法对此进行编程。
我尝试了几种方法,但都没有成功。下面是我的“杰作”的最后一个版本。请帮我完成这个任务,因为它让我恶心。谢谢,马丁
namespace DynamicCreate
{
public partial class _Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox textBox;
private TextBox[] my_dynamicTextBoxes = new TextBox[5];
private string[] textBoxValues = new string[5];
protected void Page_Load(object sender, System.EventArgs e)
{
btn_save_tb_values.Click += new EventHandler(save_btnClick);
but_load_tb.Click += new EventHandler(creat_tb_btnClick);
int i = 0;
foreach (TextBox tb in my_dynamicTextBoxes)
{
if (ViewState["c_textBox" + i.ToString()] != null)
{
tb.Text = (string)ViewState["c_textBox" + i.ToString()];
i++;
}
else
{
textBox = new TextBox();
textBox.ID = "c_textBox" + i.ToString();
my_dynamicTextBoxes[i] = textBox;
i++;
}
}
}
protected void creat_tb_btnClick(object sender, EventArgs e)
{
int i = 0;
foreach (TextBox neww in my_dynamicTextBoxes)
{
c_placeholder.Controls.Add(neww);
c_placeholder.Controls.Add(new LiteralControl("<br>"));
ViewState["c_textBox" + i.ToString()] = neww.Text;
i++;
}
}
protected void save_btnClick(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++) {}
}
}
}
<form id="form1" runat="server">
<div>
<div> <asp:PlaceHolder ID="c_placeholder" runat="server"></asp:PlaceHolder> </div>
<div> <asp:Button runat="server" ID="but_load_tb" Text="Dodaj Polja!!"/> </div>
<div> <asp:Button runat="server" ID="btn_save_tb_values" Text="Izpisi Vrednosti!" /> </div
</div>
</form>
【问题讨论】:
标签: c# asp.net textbox dynamic