C#-如何通过选中复选框以编程方式创建文本框?

时间:2018-10-26 06:57:31

标签: c# winforms

我有一个Form和一个Button。当我单击Button时,以编程方式创建一个Panel和一个CheckBox的{​​{1}};但对于TextBoxTextBoxVisible。 如果我勾选了false,我想将CheckBox更改为TextBox。 任何人都可以帮助我吗?

Visible = true

相关的事件处理程序

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);
}

2 个答案:

答案 0 :(得分:3)

您可以尝试使用 lambda 将所有相关代码保留在 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;
  };
}

答案 1 :(得分:0)

您需要在创建它的函数范围之外为文本框声明一个变量(引用),然后可以将其设置为可见的true / false。另外(较慢),您可以枚举表单(或面板)中的所有控件,找到您的文本框并将其设置为可见的true / false。