我正在开发一个小项目,当我尝试从数组生成列表时,创建的控件在添加后会被覆盖,所以我只能看到最后生成的控件。有什么东西我做得不对吗?代码如下:
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();
对于长码和我的拼写错误感到抱歉,第一次在这里发帖,我不是英文。
答案 0 :(得分:3)
您正在重复使用每次迭代中的控件(radioName和radioLogo)。因此,您只需更改现有控件的属性,而不是添加一大堆控件。
您要做的是每次都创建新的控件。例如:
foreach (string l in radios)
{
Label tempname = new Label();
PictureBox templogo = new PictureBox();
....
另一方面,在foreach循环之前调用SuspendLayout()和在foreach循环之后调用ResumeLayout()会更有效。