我动态创建了一个TextBox,当我点击按钮时,我得到了文本框的值。但是,当我单击按钮时,在动态文本框中输入的值将变为空。
以下是我的ASPX代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>
<!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>
</div>
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
<asp:ListItem>Text</asp:ListItem>
<asp:ListItem>Check</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />
</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 Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
Response.Write(Request.Form["abc"]);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createcontrol();
}
protected void createcontrol()
{
if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
}
}
}
}
答案 0 :(得分:2)
在.NET中使用动态控件并希望在回发后可以访问它们的值时,需要在页面的Page_Init方法中创建它们。本质上它不起作用,因为ViewState已经在您创建控件时设置了。有关此主题http://www.4guysfromrolla.com/articles/081402-1.aspx的详细信息,请参阅本指南。要解决此问题,请将Textbox实例化代码提升为Page_Init方法,并且一切都应该正常。