【问题标题】:Adding controls dynamically in form issue在表单问题中动态添加控件
【发布时间】:2013-11-14 01:08:47
【问题描述】:

我正在做一个小项目,当我尝试从数组生成列表时,创建的控件在添加后会被覆盖,因此我只能看到最后生成的控件。有什么我做的不对吗?代码如下:

    string[] radios = { "fillydelphia_radio", "brony_radio", "luna_radio", "alicorn_radio",
                              "sonic_radioboom", "fractured_frequencies", "ponyville_fm",
                              "everypony_radio", "wonderbolt_radio", "best_pony_radio",
                              "pegabit_sounds" };

    public List()
    {
        InitializeComponent();
        generateInfo();
        int i = 0;
        foreach (string l in radios)
        {
            Label tempname = radioName as Label;
            PictureBox templogo = radioLogo as PictureBox;
            templogo.Name = l + "logo";
            templogo.Location = new Point(templogo.Location.X, templogo.Location.Y + i);
            templogo.ImageLocation = RadiosInfo.getRadioInfo(l, "logo");
            tempname.Name = l + "name";
            tempname.Location = new Point(tempname.Location.X, tempname.Location.Y + i);
            tempname.Text = RadiosInfo.getRadioInfo(l, "name");
            SuspendLayout();
            this.Controls.Add(tempname);
            this.Controls.Add(templogo);
            ResumeLayout();
            i += 50;
        }
    }

    private PictureBox radioLogo = new PictureBox();
    private Label radioName = new Label();
    private Label radioArtist = new Label();
    private Label radioSong = new Label();
    private Label radioGenre = new Label();

对不起,我的代码太长了,我的拼写错误,第一次在这里发帖,我不是英语。

【问题讨论】:

    标签: c# .net arrays winforms


    【解决方案1】:

    您在每次迭代中重复使用控件(radioName 和 radioLogo)。因此,您只需更改现有控件的属性,而不是添加一大堆控件。

    您需要做的是每次都创建新控件。例如:

    foreach (string l in radios)
    {
        Label tempname = new Label();
        PictureBox templogo = new PictureBox();
        ....
    

    另一方面,在 foreach 循环之前调用 SuspendLayout() 并在 foreach 循环之后调用 ResumeLayout() 会更有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2017-02-02
      相关资源
      最近更新 更多