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

我有一个带有一个按钮的表格.当我单击按钮时,以编程方式创建一个带有一个CheckBox和一个TextBox的面板;但对于TextBox,Visible为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);
}

相关事件处理程序为

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

解决方法:

您可以尝试使用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;
  };
}
上一篇:c#-使用带有固定位置文本的ScrollableControl的自定义控件


下一篇:识别Web浏览器的垂直滚动在C#中的最后位置到达