如何根据整数变量的值动态创建许多标签和文本框?

2024-02-27

当我们知道“n”的值时,例如单击“显示”按钮后,有什么方法可以动态创建和显示带有“n”个相应文本框的“n”个标签。

如果有任何事情让您不明白我的问题,请告诉我。谢谢你!

我正在使用 VS C# Express 2010 Windows 窗体。


我将创建一个用户控件,其中包含一个标签和一个文本框,并简单地创建该用户控件的实例“n”次。如果您想了解更好的方法并使用属性从用户控件访问标签和文本框的值,请告诉我。

简单的方法是:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

上面的代码假设您有一个按钮btnDisplay它有一个onClick事件分配给btnDisplay_Click事件处理程序。您还需要知道 n 的值,并需要一种方法来确定所有控件的放置位置。控件还应该指定宽度和高度。

要使用用户控件来完成此操作,只需执行此操作即可。

好的,首先创建一个新的用户控件并在其中放置一个文本框和标签。

假设他们被称为txtSomeTextBox and lblSomeLabel。在后面的代码中添加这段代码:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

现在生成用户控件的代码将如下所示(MyUserControl 是您为用户控件指定的名称):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

当然,您可以在用户控件中创建更多方法来访问属性并设置它们。或者,如果您需要访问很多内容,只需输入这两个变量,您就可以直接访问文本框和标签:

public TextBox myTextBox;
public Label myLabel;

在用户控件的构造函数中执行以下操作:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

然后在你的程序中,如果你想修改其中任何一个的文本值,就这样做。

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

希望它有帮助:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据整数变量的值动态创建许多标签和文本框? 的相关文章

随机推荐