【发布时间】:2012-04-02 04:31:10
【问题描述】:
我正在创建一个 asp.net 页面,该页面在 updatepanel 中有一个值为 0、1、2、3、4 的下拉列表
当用户点击 0 元素时,我想创建一个文本框和一个按钮。当用户单击按钮时,文本框的值应显示在标签中,无需回发
当用户单击元素 1 时,应显示两个文本框,元素 2 为 3,依此类推。
请提出解决方案。
[已编辑]
私有 int tblRows = 5; 私人 int tblCols = 1;
protected void Page_Load(object sender, EventArgs e)
{
CreateDynamicTable();
}
private void CreateDynamicTable()
{
if( ViewState["tbl"] != null && ViewState["tbl"].ToString() == "true"){
// Fetch the number of Rows and Columns for the table
// using the properties
// Now iterate through the table and add your controls
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.ID = "txt-" + i.ToString() + "-" + j.ToString();
txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
// Add the control to the TableCell
tc.Controls.Add(txtBox);
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
}
}
protected void btnSet_Click(object sender, EventArgs e)
{
foreach (TableRow tr in tbl.Controls)
{
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is TextBox)
{
Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
Response.Write("<br/>");
}
}
protected override object SaveViewState()
{
object[] newViewState = new object[2];
List<string> txtValues = new List<string>();
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox)
{
txtValues.Add(((TextBox)cell.Controls[0]).Text);
}
}
}
newViewState[0] = txtValues.ToArray();
newViewState[1] = base.SaveViewState();
return newViewState;
}
protected override void LoadViewState(object savedState)
{
//if we can identify the custom view state as defined in the override for SaveViewState
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (txtValues.Length > 0)
{
//re-load tables
CreateDynamicTable();
int i = 0;
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox && i < txtValues.Length)
{
((TextBox)cell.Controls[0]).Text = txtValues[i++].ToString();
}
}
}
}
//load the ViewState normally
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateDynamicTable();
}
谢谢
【问题讨论】:
-
我可以使用回发创建动态文本框(没有更新面板),但是当我使用更新面板时,它不起作用。文本框只需要在下拉选择的索引更改时创建
-
能出示相关代码吗?
-
@Coder 请查看代码...我想使用更新面板和下拉列表来完成
-
我的意思是显示更新面板和下拉列表的相关标记代码。
标签: asp.net asp.net-ajax