C# - How to Create a textbox programmatically by checked a Checkbox?

Viewed 102

I have a Form with one Button. When I click the Button, then programmatically create a Panel with one CheckBox and a TextBox; but for the TextBox the Visible is false. If I checked the CheckBox, I want to change my TextBox to Visible = true. Any body can help me?

public void CreateSlide(string name, string title, string desc) 
{
    var PanelOrder = new Panel() 
    { 
        Name = name,
        Size = new Size(395, 33),
        BorderStyle = BorderStyle.FixedSingle,
        Location = new Point(203, 157)
    };

    var ckOrder = new CheckBox()
    {
        Name = name,
        Text = "Order",
        Size = new Size(102, 21),
        Location = new Point(3, 5),
        FlatStyle = FlatStyle.Flat,
        Font = new Font("Segoe UI", 10, FontStyle.Bold)
    };

    ckOrder.CheckedChanged += new EventHandler(this.ckBoxOrder_CheckedChanged);

    var TxtQty = new TextBox
    {
        Name = name,
        Text = "1",
        Visible = false,
        BorderStyle = BorderStyle.FixedSingle,
        Size = new Size(100, 25),
        Location = new Point(290, 3)
    };

    PanelOrder.Controls.Add(ckOrder);
    PanelOrder.Controls.Add(TxtQty);
}

Relevant event handler is

private void ckBoxOrder_CheckedChanged(object sender, EventArgs e)
{
    if (((CheckBox)sender).Checked == true) 
    {
        // ??? TxtQty.Visible = true; // <- doesn't compile
    }
    else 
    {  
        // ??? TxtQty.Visible = false; // <- doesn't compile
    }
 }
2 Answers

You can try using lambda in order to keep all the relevant code within CreateSlide:

public void CreateSlide(string name, string title, string desc) {
  var PanelOrder = new Panel() { 
    Name = name,
    Size = new Size(395, 33),
    BorderStyle = BorderStyle.FixedSingle,
    Location = new Point(203, 157),
    Parent = this // <- Put PanelOrder panel on the form
  };

  var ckOrder = new CheckBox() {
    Name = name,
    Text = "Order",
    Size = new Size(102, 21),
    Location = new Point(3, 5),
    FlatStyle = FlatStyle.Flat,
    Font = new Font("Segoe UI", 10, FontStyle.Bold),
    Parent = PanelOrder // <- Put ckOrder on the PanelOrder panel
  };

  var TxtQty = new TextBox() {
    Name = name,
    Text = "1",
    Visible = false,
    BorderStyle = BorderStyle.FixedSingle,
    Size = new Size(100, 25),
    Location = new Point(290, 3),
    Parent = PanelOrder // <- Put TxtQty on the PanelOrder panel
  };

  // lambda function
  ckOrder.CheckedChanged += (s, e) => {
    TxtQty.Visible = ckOrder.Checked;
  };
}

you need to declare a variable (reference) for the textbox outside the scope of the function that creates it, then you can set it to visible true/false. alternatively (slower) you can enumerate all controls in the form (or the panel), find your text box and set it to visible true/false.

Related