问题
I am trying to create link labels dynamically using foreach . I am setting the text of each linklabel to a string which is stored in flatestgames string array and whose links are stored in flatestlinks string array. But it is throwing a null reference exception at the line flg[i].Text = s though s is not set to null. Please help me out. Below is the code snippet:
if (!(flatestgames == null || flatestgames.Length < 1))
{
i = 0;
LinkLabel[] flg = new LinkLabel[10];
foreach (string s in flatestgames)
{
flg[i].Text = s;
flg[i].Links.Add(0, s.Length, flatestlinks[i]);
Point p = new Point(43, 200 + 23 * i);
flg[i].Location = p;
flg[i].Visible = true;
flg[i].Show();
this.Controls.Add(flg[i]);
i++;
}
}
回答1:
Try flg[i] = new LinkLabel();
in foreach loop
if (!(flatestgames == null || flatestgames.Length < 1))
{
i = 0;
LinkLabel[] flg = new LinkLabel[10];
foreach (string s in flatestgames)
{
flg[i] = new LinkLabel();
flg[i].Text = s;
flg[i].Links.Add(0, s.Length, flatestlinks[i]);
Point p = new Point(43, 200 + 23 * i);
flg[i].Location = p;
flg[i].Visible = true;
flg[i].Show();
this.Controls.Add(flg[i]);
i++;
}
}
回答2:
Are you sure, that the length of your flatestgames
array less than 10? You have to check this at first and declare your:
LinkLabel[] flg = new LinkLabel[10];
as:
LinkLabel[] flg = new LinkLabel[flatestgames.Length];
I think you get this exception, because in foreach you try to get more than 10 entities as you declared.
来源:https://stackoverflow.com/questions/17608784/dynamically-creating-link-labels-using-foreach-in-c-sharp