Question

I have a TextBox and a postback Button.

<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged1"     EnableViewState="false"></asp:TextBox><span></span>
<asp:Button ID="Button1" runat="server" Text="Button" />

So, I need to fire TextChanged event only when text changed(what an irony), like it fires when EnableViewState is true. I can't unsubscribe event or subscribe it somwhere else or enable ViewState. I've tried to save text from the TextBox in HiddenField and then check if it's changed. Here's the code

 protected void Page_Load(object sender, EventArgs e) {
    if (HiddenField1.Value != TextBox1.Text) {
        HiddenField1.Value = TextBox1.Text;
        TextBox1.Text = HiddenField1.Value;
    }           
}

But I have no idea what to do when text is not changed and not to fire the event.

Was it helpful?

Solution

The problem was in saving values from TextBox when ViewState disabled. Saving it in HiddenField is not a good idea, because we can take value from HiddenField on Page_Load, but we need to take it on TextBox init. However, if we save TextBox to Session variable, this problem will disappear. Here's the code:

protected void TextBox1_TextChanged1(object sender, EventArgs e) {
    Session["text"] = TextBox1.Text;
}
protected void TextBox1_Init(object sender, EventArgs e) {
    if(Session["text"]!=null)TextBox1.Text = Session["text"].ToString();
}

Save values in session variable on textchanged event and restore it on textbox init. Comparison run on framework level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top