I found an issue in some of my code and can't figure out the reason why. I'm using .Net 4.5. Can anyone please tell me the difference between these two cases? I tried a few different things such javascript to disable via Page.ClientScript
or on the body onload event but I'm not getting what I want (TextBox2 is "" and TextBox1 is "Hello, TextBox1"). When I comment out tmp.Enable = false
everything is fine. I'd like to be able to disable both controls but still access the Text value. Works fine for "TextBox1" but not "tmp" aka "TextBox2".
The reason for !IsPostBack and TextBox2 being created during the Page_Load is because I'm dynamically creating X number of controls and setting their value from a datareader. they can then be modified by the user and saved to the table. There must be a way!
This post sounds like my problem but I'm getting different results than them.
ASP.Net ViewState doesn't work when Control become Enable=False
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function t() {
document.getElementById("TextBox1").disabled = true;
document.getElementById("TextBox2").disabled = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="Panel1">
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:Button runat="server" ID="button1" OnClick="button1_Click" />
</asp:Panel>
</div>
</form>
</body>
</html>
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { TextBox1.Text = "Hello, TextBox1"; }
TextBox1.Enabled = false;
TextBox tmp = new TextBox();
tmp.ID = "TextBox2";
if (!IsPostBack) { tmp.Text = "Hello, TextBox2"; }
tmp.Enabled = false;
Panel1.Controls.Add(tmp);
}
protected void button1_Click(object sender, EventArgs e)
{
TextBox tmp = ((TextBox)Page.FindControl("TextBox2"));
if(tmp != null)
{
tmp.Text.ToString();
}
TextBox1.Text.ToString();
}
}
UPDATE: Per haraman's suggestion I was able to get it working by making the following changes:
protected void Page_PreInit(object sender, EventArgs e)
{
TextBox tmp = new TextBox();
tmp.ID = "TextBox2";
Panel1.Controls.Add(tmp);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { TextBox1.Text = "Hello, TextBox1"; }
TextBox1.Enabled = false;
if (!IsPostBack) { ((TextBox)Page.FindControl("TextBox2")).Text = "Hello, TextBox2"; }
((TextBox)Page.FindControl("TextBox2")).Enabled = false;
}
protected void button1_Click(object sender, EventArgs e)
{
TextBox tmp = ((TextBox)Page.FindControl("TextBox2"));
if (tmp != null)
{
tmp.Text.ToString();
}
TextBox1.Text.ToString();
}