Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist if checkbox is clicked through postback

I have a checkbox that is set to "false" as default in the aspx. Then there is a function that determines whether it is true or false, the problem is that when on the page there is a textbox and this textbox has a TextChange Event on it, when i type something in the textbox and then go to the checkbox which at this time is visible the first time i click the whole page postbacks and resets the checkbox to unchecked.. then i need to click it again and then it sticks.. what can I do to make it stick at the first click?

Can I use some javascript for this or what do you think my options are?

 protected void myTextbox_TextChanged(object sender, EventArgs e)
    {
        ShowCheckBox(true);
    }

  private void ShowCheckBox(bool ckVal)
   {
      myCheckBox.Visible = ckVal;
   }
like image 965
user710502 Avatar asked Oct 17 '11 14:10

user710502


4 Answers

why not add the textbox inside an update panel something like this:

<asp:UpdatePanel runat="server" ID="test">
    <ContentTemplate>
        <asp:TextBox ID="TEXTBOX" runat="server" Visible="true" AutoPostBack="true"
            OnTextChanged="checkUser" >Page Name</asp:TextBox>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="TEXTBOX" EventName="TextChanged" />
    </Triggers>
</asp:UpdatePanel>
like image 166
Wahtever Avatar answered Oct 01 '22 03:10

Wahtever


My best guess is that your check box initialization (what sets Checked to false) runs on every postback. E.g. change this

protected void Page_Load(object sender, EventArgs e)
{
    myCheckBox.Checked = false;
}

to this

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        myCheckBox.Checked = false;
}

However, we'll need to see some more code before we can effectively assist you. Part of the issue might be that ViewState is not persisted when the control is not Visible. If all that you want to do is show/hide it, use javascript as others have suggested.

Here's an example with jQuery:

$(document).ready(function (){
  $("#myTextBox").change(function() {
    $("#myCheckBox").show();
  });
});
like image 38
jrummell Avatar answered Sep 30 '22 03:09

jrummell


If i was you,i would write some clode in client side to show the check box or hide it, writting suck code in server side is not good and needs extra roundtrip also you can use an updatepanel to do that

like image 20
DeveloperX Avatar answered Sep 30 '22 03:09

DeveloperX


Checkbox, if .Visible = false is not rendered to the client. So when postback happens the default value of "false" is what it's set to.

You can render control all the time and toggle visibility via CSS so the checkbox is always part of the control tree and its ViewState is persisted.

style="display:none" and style="display:inline"

like image 25
Leon Avatar answered Oct 01 '22 03:10

Leon