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.

1
  • 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. Commented Jan 12, 2016 at 10:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

If i had to use postback, what would I have to change so it can work ? Adding AutoPostBack="true" ? And then something else (ViewState) ?
Client Side: 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 msdn.microsoft.com/en-us/library/… Have fun
0

Set AutoPostBack = "true" in your checkbox.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.