動態新增Textbox並取值
剛好看論壇有人問類似的問題
自己練習的筆記
感謝91大大指點....
程式做些許微調......
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamic_add_textbox.aspx.cs" Inherits="dynamic_add_textbox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Height="23px" onclick="Button1_Click"
Text="Button" Width="51px" /> <asp:Button ID="Button2" runat="server"
Text="Button" onclick="Button2_Click" Width="63px" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class dynamic_add_textbox : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["TextBoxCount"] = 0;
}
if (ViewState["TextBoxCount"].ToString() != "0")
{
for (int i = 1; i <= int.Parse(ViewState["TextBoxCount"].ToString()); i++)
{
TextBox DyTextBox = new TextBox();
Label templabel = new Label();
//這邊只測試抓最後一個動態產生的值,如有興趣可以自行改list存放
{
string value = Request.Form.Get("DyTextBox" + ViewState["TextBoxCount"].ToString());
}
this.Form.Controls.Add(DyTextBox);//元件加入 Controls 裡
this.Form.Controls.Add(templabel);
DyTextBox.ID = "DyTextBox" + i;
templabel.Text = ("
");
}
}
string valueE = Request.Form.Get("DyTextBox" + (int.Parse(ViewState["TextBoxCount"].ToString())));
Response.Write(valueE);
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["TextBoxCount"] = int.Parse(ViewState["TextBoxCount"].ToString()) + 1;
// for (int i = 1; i <= int.Parse(ViewState["TextBoxCount"].ToString()); i++)
{
TextBox DyTextBox = new TextBox();
Label templabel = new Label();
this.Form.Controls.Add(DyTextBox);//元件加入 Controls 裡
this.Form.Controls.Add(templabel);
DyTextBox.ID = "DyTextBox" +ViewState["TextBoxCount"].ToString();
templabel.Text = ("
");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
}
}
大家一起加入blogads 賺零用錢!!