5

I added a checkbox to my form.

When the checkbox is checked, some information (TextBox, Label etc.) should appear right under the checkbox.

How can I do this?

Code:

<asp:CheckBox ID="CheckBox1" runat="server" 
        oncheckedchanged="CheckBox1_CheckedChanged" />

C#:

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
        
}

5 Answers 5

11

Don't forget autopostback = true

<asp:CheckBox ID="CheckBox1" runat="server" oncheckedchanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
<asp:Panel runat="server" ID="panel1"></asp:Panel>

-

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    panel1.Controls.Add(new Label { Text = "Text goes here" });
}

This allows you to add any control you want.

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

Comments

2

Just add TextBox, Label etc. controls and make them invisible. Then in the CheckBox1_CheckedChanged function make them visible. This is done by setting the bool Visible property

<asp:CheckBox ID="CheckBox1" runat="server" oncheckedchanged="CheckBox1_CheckedChanged" />
<asp:TextBox ID="textBox" runat="server" Visible=false />

and

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    textBox.Visible = true;
}

1 Comment

you should wrap all your controls in a panel. It will be more simple to change the visibility of a single panel control than a lot of other controls. Moreover, the structural html tags will also be shown/hidden along the server controls
1

Add a new literal control under your checkbox tags,

<asp:Literal id="lblMsg" runat="server"/>

then in your CheckBox1_CheckedChanged event to this:

lblMsg.Text = "Checked";

and yes set the AutoPostBack property of your checkbox to true

Comments

1

I would suggest doing this using javascript. Your users won't have to "postback" and the feeling on the application will be better, and you will reduce the server charge.

Using jQuery, you can use something like this:

<script language="javascript" type="text/javascript">
 $(document).ready(function(){
      $("#chk").onclick(function() {
          $("#content").toggle();
      });
  });
</script>
<input type="Checkbox" id="chk"/>
<div id="content" style="display:none">
       <asp:TextBox runat="Server" id="oneOfYourControls" />
</div>

jQuery is not mandatory... you can use standard simple getElementById().

The only drawback, is that you cannot dynamically build the content, but in most case it's a not actually a matter

Comments

0

In Checked Changed Event write your code like this:

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
     Label1.Text = "Text";
}

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.