这是另一种方法。您可以在 asp.net 页面中有一个占位符。在后面的代码中动态创建一个带有动态文本框的表格并将其插入到占位符内。在这种情况下,您可以控制每个文本框的 ID。在回发时输入到文本框中的值将被保留(因为 ID 是确定的,您也可以进行 javascript 操作)
这是aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="Test2.DynamicControls" %>
<!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:PlaceHolder ID="PHDynamicTable" runat="server"></asp:PlaceHolder>
<asp:Button runat="server" ID="btnSubmit" Text="Submit"
onclick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
背后的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test2
{
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
CreateTextBoxesInTable();
}
private void CreateTextBoxesInTable()
{
PHDynamicTable.Controls.Clear();
List<string> X = new List<string>() { "A", "B", "C" };
List<string> Y = new List<string>() { "1", "2", "3", "4" };
Table table = new Table();
table.ID = "dynamicTable";
TableRow tr;
foreach (string y in Y)
{
tr = new TableRow();
foreach (string x in X)
{
TableCell tc = new TableCell();
TextBox textBox = new TextBox();
textBox.ID = "txt_" + x + y;
tc.Controls.Add(textBox);
tr.Cells.Add(tc);
}
table.Rows.Add(tr);
}
PHDynamicTable.Controls.Add(table);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (PHDynamicTable.Controls.Count > 0)
{
Table dynamicTable = (Table)PHDynamicTable.FindControl("dynamicTable");
if (dynamicTable != null)
{
foreach (TableRow tr in dynamicTable.Rows)
{
foreach (TableCell tc in tr.Cells)
{
TextBox textBox = (TextBox)tc.Controls[0];
string text = textBox.Text;
//Do whatever you want with the control
}
}
}
}
}
}
}
几张截图
带有数据的输入屏幕
回发(提交)
提交后