2

I want to create a UserControl in which I will have a checkbox and a textbox. If the checkbox is checked then enable property of textbox is true else it is false.

This is what I have in my page :

<form id="form1" runat="server">
    <div>
        <custom:NullableTextBox ID="NullableTextBox1" OnCheckedChanged="NullableTextBox1_OnCheckedChanged" runat="server"></custom:NullableTextBox>
    </div>
</form>

And this is the class of my UserControl :

public partial class NullableTextBox : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public NullableTextBox()
    {
        CheckBox1.CheckedChanged += new EventHandler(CKB_CheckedChanged);

        this.Controls.Add(CheckBox1);
        this.Controls.Add(TextBox1);
    }

    private CheckBox CheckBox1 = new CheckBox();
    private TextBox TextBox1 = new TextBox();

    private void CKB_CheckedChanged(object sender, EventArgs e)
    {
        if (CheckBox1.Checked)
        {
            TextBox1.Enabled = true;
        }
        else
        {
            TextBox1.Text = string.Empty;
            TextBox1.Enabled = false;
        }
    }
}

Nothing is happening when I check or uncheck the checkbox and I would like it to be updated instantly without doing a postback.

Stan
  • 391
  • 2
  • 5
  • 21
  • How can I handle postback ? I may do a postback when CheckedChanged event is raised and add an updatepanel in aspx page but I do not know how to do it. – Stan Jan 12 '16 at 10:41

2 Answers2

0

You do a server side event but don't want to have postback. That means you need to add it to client side with JavaScript.

onclick="document.getElementById('TextBox1').disabled=this.checked;"

How to disable textbox depending on checkbox checked

Hope that helps

Community
  • 1
  • 1
Edgaras
  • 154
  • 9
  • If i had to use postback, what would I have to change so it can work ? Adding AutoPostBack="true" ? And then something else (ViewState) ? – Stan Jan 12 '16 at 10:48
  • Client Side: https://jsfiddle.net/wsqf0eov/ Server Side: set AutoPostBack = "true". private void checkBox1_CheckedChanged(object sender, EventArgs e) { textBox1.Enabled = checkBox1.Checked; } Something like that. Other thing is that you are creating control every time page loads. Try to create it NOT on postback. Here is the reference in msnd https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx Have fun – Edgaras Jan 12 '16 at 11:48
0

Set AutoPostBack = "true" in your checkbox.

Rai Vu
  • 1,595
  • 1
  • 20
  • 30