2013-07-12 73 views
0

我正在尝试使用foreach动态创建链接标签。我将每个linklabel的文本设置为一个存储在flatestgames字符串数组中的字符串,其链接存储在flatestlinks字符串数组中。 但它是在行flg [i] .Text = s处引发空引用异常,尽管s未设置为null。 请帮我一把。 下面的代码片段:在c中使用foreach动态创建链接标签#

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++; 
      } 
     } 

回答

0

你确定,你flatestgames数组的长度小于10?你必须在第一次检查,并宣布该你:

LinkLabel[] flg = new LinkLabel[10];

为:

LinkLabel[] flg = new LinkLabel[flatestgames.Length];

我觉得你这个例外,因为的foreach您尝试获得超过10个实体你宣布。

2

在foreach循环尝试flg[i] = new LinkLabel();

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++; 
      } 
     } 
+0

你应该在你的答案,凡在foreach循环,他需要做到这一点,这是为什么。 (这是正确的btw +1) – Sayse

+0

现在它在下一行抛出相同的异常 –

+0

@PrabhanjanBhat - 您应该更新您的问题,然后更新信息(即更新的代码源) – Sayse