我正在尝试创建一个Windows应用程序,我希望在面板按钮内单击时显示一组控件(组合框,文本框和按钮)。
我已经创建了一个代码来创建控件一次,但我想一次又一次地创建它们,只需按一下另一个按钮。
我正在使用的代码是
public partial class Employee_PayHeads_add : Form
{
private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ComboBox combohead = new ComboBox();
public Employee_PayHeads_add()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.btnAdd.BackColor = Color.Gray;
this.btnAdd.Text = "Remove";
this.btnAdd.Location = new System.Drawing.Point(240, 25);
this.btnAdd.Size = new System.Drawing.Size(70, 25);
this.txtBox.Text = "";
this.txtBox.Location = new System.Drawing.Point(150, 25);
this.txtBox.Size = new System.Drawing.Size(70, 40);
this.combohead.Location = new System.Drawing.Point(10, 25);
panel1.Controls.Add(btnAdd);
panel1.Controls.Add(txtBox);
panel1.Controls.Add(combohead);
}
如果数字控件与空格重叠,我还想在面板中使用垂直滚动条。
提前致谢
答案 0 :(得分:0)
在按钮单击事件内创建新对象,而不是使用之前声明的对象。
尝试类似的东西:
public partial class Employee_PayHeads_add : Form
{
private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ComboBox combohead = new ComboBox();
private int txtBoxStartPosition = 150;
private int btnAddStartPosition = 240;
private int comboheadStartPosition = 10;
}
public Employee_PayHeads_add()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextBox newTxtBox = new TextBox();
Button newBtnAdd = new Button();
ComboBox newCombohead = new ComboBox();
newBtnAdd.BackColor = Color.Gray;
newBtnAdd.Text = "Remove";
newBtnAdd.Location = new System.Drawing.Point(btnAddStartPosition, 25);
newBtnAdd.Size = new System.Drawing.Size(70, 25);
newTxtBox.Text = "";
newTxtBox.Location = new System.Drawing.Point(txtBoxStartPosition, 25);
newTxtBox.Size = new System.Drawing.Size(70, 40);
newCombohead.Location = new System.Drawing.Point(comboheadStartPosition, 25);
panel1.Controls.Add(newBtnAdd);
panel1.Controls.Add(newTxtBox);
panel1.Controls.Add(newCombohead);
txtBoxStartPosition += 50;
btnAddStartPosition += 50;
comboheadStartPosition += 50;
}
答案 1 :(得分:0)
我还没有尝试过你的代码,但它表明它总是在每个点击事件上创建新控件,但是因为你已经为按钮指定了硬件加工位置,所以它必须创建相互重叠的新控件。所以你可以动态地改变位置,希望它可以工作
答案 2 :(得分:-1)
如果要反复添加控件,则必须创建新控件。所以不要像你必须那样在你的表单中定义它们:
private void button1_Click(object sender, EventArgs e)
{
Button btnAdd = new Button();
btnAdd.BackColor = Color.Gray;
btnAdd.Text = "Remove";
btnAdd.Location = new System.Drawing.Point(240, 25);
btnAdd.Size = new System.Drawing.Size(70, 25);
TextBox txtBox = new TextBox();
txtBox.Text = "";
txtBox.Location = new System.Drawing.Point(150, 25);
txtBox.Size = new System.Drawing.Size(70, 40);
ComboBox combohead = new ComboBox();
combohead.Location = new System.Drawing.Point(10, 25);
panel1.Controls.Add(btnAdd);
panel1.Controls.Add(txtBox);
panel1.Controls.Add(combohead);
}
现在,您可以在班级上删除这些私人声明。