简体   繁体   English

将组件动态添加到Windows窗体C#

[英]Dynamically add components to windows form C#

I am trying to add a list of Strings to be used as the text component of labels on a windows form. 我试图添加一个字符串列表,用作Windows窗体上标签的文本组件。 Below is the code i am using to do this. 以下是我用来执行此操作的代码。 I have it generating a message box to show me what is being created, but when i add them to the form, only the first string is ever shown on the form, despite a message box popping up for each string indicating the list is populated correctly. 我让它生成一个消息框来显示正在创建的内容,但是当我将它们添加到表单时,尽管第一个字符串弹出一个消息框,表明列表已正确填充,但表单上只显示了第一个字符串。 。 Any help would be great. 任何帮助都会很棒。

List<Label> labelList;

    public void ShowDialog(List<String> columns)
    {
        labelList = new List<Label>();
        Form updateDialog = new Form();
        updateDialog.Width = 500;
        updateDialog.Height = 500;


        for (int i = 0; i < columns.Count(); i++ )
        {
            //Label label = new Label() {Text=columns[i].ToString() };

            labelList.Add(new Label() {Text=columns[i].ToString()});
        }

        for (int j = 0; j < labelList.Count(); j++ )
        {

            updateDialog.Controls.Add(labelList[j]);
            MessageBox.Show(labelList[j].Text.ToString());
        }

You need to set the location of the created labels. 您需要设置创建的标签的位置。 They are positioned on top of each other at location (0, 0). 它们位于位置(0,0)彼此重叠。

Controls are being added to the form , but they are not visible to you. 控件已添加到form ,但是您看不到它们。 Just set the different location for each Label and you'll see them. 只需为每个Label设置不同的位置,您就会看到它们。

You can also precise your code by using 1 loop instead: 您还可以通过使用1循环来精简代码:

int yAxis = 10;
for (int i = 0; i < columns.Count(); i++ )
{
    //create label
    Label newLbl = new Label() {Text=columns[i].ToString()};
    newLbl.Location = new Point(10, yAxis * i); //will create a column of all labels, you can use your oown logic too

    //add to list
    labelList.Add(newLbl);

    //add to form
    updateDialog.Controls.Add(newLbl);

    //show on msg box
    MessageBox.Show(newLbl.Text.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM