62,052
社区成员
发帖
与我相关
我的任务
分享
Page_Load(object sender,EventArgs e)
{
int totalCount;
try
{
totalCount = (int)ViewState["NowCount"];
}
catch
{
totalCount = 0;
}
if(totalCount != 0)
{
BulidTextBox(totalCount );
}
}
void BulidTextBox(int num)
{
for(int i = 0;i<num;i++)
{
TextBox tb = new TextBox();
tb.ID= "tb" + nowCount.ToString();
//容器
panel1.Controls.Add(tb);
}
btn_click(object sender,EventArgs e)
{
int nowCount ;
try
{
nowCount = (int)ViewState["NowCount"];
}
catch
{
nowCount = 0;
}
TextBox tb = new TextBox();
tb.ID= "tb" + nowCount.ToString();
//tb.Text = "Text";
//tb.CssName = "cssname";
//tb.Width = 20;
//tb.MaxLength = 0;
panel1.Controls.Add(tb);
ViewState["NowCount"] = nowCount + 1;
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextBox.aspx.cs" Inherits="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>
<script language="javascript" type="text/javascript">
var count=0;
function AddTextBox()
{
var div=document.getElementById('div');
div.insertAdjacentHTML("beforeEnd","<input type='text' id='txt"+count+"' name='txt"+count+"' /><br>");
count++;
}
function SetValue()
{
document.getElementById('<%=hidCount.ClientID %>').value=count;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="div">
</div>
<input type="button" id="btnAdd" value="增加" onclick="AddTextBox()" />
<asp:Button ID="btnSubmit" runat="server" Text="提交" OnClientClick="SetValue()" OnClick="btnSubmit_Click" />
<asp:HiddenField ID="hidCount" runat="server" />
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
public partial class TextBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
hidCount.Value = "0";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
List<string> l = new List<string>();
int count = 0;
int.TryParse(hidCount.Value, out count);
for (int i = 0; i < count; i++)
{
l.Add(string.IsNullOrEmpty(Request.Form["txt" + i.ToString()]) ? null : Request.Form["txt" + i.ToString()]);
}
StringBuilder sb = new StringBuilder();
sb.Append("<script>document.getElementById('div').innerHTML=\"");
for (int i = 0; i < l.Count; i++)
{
sb.Append("<input type='text' id='txt" + i + "' name='txt" + i + "' value='" + (l[i] == null ? "" : l[i]) + "' /><br>");
}
sb.Append("\";count=" + hidCount.Value + ";</script>");
ClientScript.RegisterStartupScript(GetType(), "AddTextBox", sb.ToString());
}
}