且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Windows应用程序中动态添加控件?

更新时间:2023-10-12 19:57:22



您可以通过创建控件的新实例来添加多个控件.

Hi,

You can Add multiple control by creating a new instance of the control.

var p1 = new Panel()
var controlCount = Convert.ToInt(textbox1.Text);
for(i=0;i<controlcount;i++)>
{
  var c1 = new ComboBox();
  // set all your required property of c1 here.
  p1.Controls.Add(c1);
}



这样可以在面板中添加多个控件.关于垂直添加控件的第二个问题,可以使用 StackPanel 代替Panel控件添加动态创建的控件.

谢谢
-Amit Gajjar



This is how you can add multiple controls in your panel. And for your second issue regarding adding your control vertically, you can use StackPanel instead of Panel control to add your dynamically created controls.

Thanks
-Amit Gajjar


我希望您引用的是Windows Form Application.如果是这样,请遵循以下内容:

I hope you are referring Windows Form Application. If so follow the the stuff below:

this.SuspendLayout();
TextBox txtbx = new TextBox();
txtbx.Text = existingTextBox.Text;
this.YourPanel.Controls.Add(txtbx);
//do similar stuff for combobox here.
this.ResumeLayout();


int gap=10;
for(i=0;i<convert.toint32(txtnum.text);i++)>
{
    combobox c = new Combobox();
    textbox t = new textbox();
    pnl.controls.add(c);
    pnl.controls.add(t);
//for dynamically set position of textbox & combobox perform some calculations like below
    t.location=new point(txtNum.Location.x,txtNum.Location.Y + (txtNum.height * i) + gap);
    c.location=new point(txtNum.Location.x+ txtNum.width + gap,txtNum.Location.Y + (txtNum.height * i) + gap);
}


祝您编码愉快!
:)


Happy Coding!
:)