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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top