1

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

    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();

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

4

1 回答 1

3

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

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

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

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

于 2013-11-14T01:14:23.740 回答