【问题标题】:Dynamic button and create textbox动态按钮和创建文本框
【发布时间】:2015-11-17 05:24:27
【问题描述】:

我在 c# 表单上有一个文本框和按钮,用户可以输入数字。我创建了一个用户想要的标签,每个标签都有一个按钮。在这里,如果我点击这些按钮,我想创建文本框,但如果用户继续点击,我想要创建更多的文本框。

Button[] Btn= new Button[10];
for (int i = 0; i < labelNumber; i++)
{
    Btn[i] = new Button();
    Btn[i].Text = "Add";
    Btn[i].Location = new Point(40, 100 + i * 29);
    Btn[i].Size = new Size(50,20);
    this.Controls.Add(Btn[i]);
    Btn[i].Click += new EventHandler(addNewTextbox); 
}

关于上面的代码;例如;如果labelNumber == 3 所以我有 3 个标签和 3 个按钮,如果我点击添加按钮,我想在这个标签附近创建文本框。

private void addNewTextbox(object sender, EventArgs e)
{
    TextBox[] dynamicTextbox = new TextBox[10];
    Button dinamikButon = (sender as Button);
    int yLocation = (dinamikButon.Location.Y - 100) / 29;
    //int xLocation =  dinamikButon.Location.X - 100;
    dynamicTextbox[yLocation] = new TextBox();
    dynamicTextbox[yLocation].Location = new Point(100, 100 + yLocation * 29);
    dynamicTextbox[yLocation].Size = new Size(40, 50);
    this.Controls.Add(dynamicTextbox[yLocation]);

}

我在这里更改了文本框的 y 坐标,但对于 X,我不能这样做。如果我改变了这个

dynamicTextbox[yLocation].Location = new Point(100*x, 100 + yLocation * 29);
x++;

排序等于所有。

Label1 Button1
Label2 Button2
Label3 Button3

如果我点击Button1 4 次,它必须在label1 旁边创建4 个文本框。如果我点击Button2 2 次,它必须在label2 旁边创建2 个文本框 请帮助我。

【问题讨论】:

  • 如果用户继续点击同一个按钮会发生什么?可以创建多少个文本框有限制吗?
  • 我想要 crete 文本框。我没想到,但 6 就足够了。标签1 按钮1 文本框1 文本框2 文本框3 标签2 按钮2 标签3 按钮3 @IvanStoev

标签: c#


【解决方案1】:

最简单的方法是在按钮的Tag 属性中保留一个包含已创建文本框的列表,如下所示

private void addNewTextbox(object sender, EventArgs e)
{
    var button = (Button)sender;
    var textBoxes = button.Tag as List<TextBox>;
    if (textBoxes == null)
        button.Tag = textBoxes = new List<TextBox>();
    var textBox = new TextBox();
    textBoxes.Add(textBox);
    textBox.Location = new Point(100 * textBoxes.Count, button.Top);
    textbox.Size = new Size(40, 50);
    this.Controls.Add(textBox);
}

这样你不仅可以添加一个新的文本框,还可以根据需要随时轻松确定每个按钮创建的文本框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多