0

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

2 Answers2

3

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++;
            }
        }
Satish Bejgum
  • 223
  • 2
  • 16
  • You should include in your answer, where in foreach loop he needs to do this and why. (This is correct btw +1) – Sayse Jul 12 '13 at 06:53
  • @PrabhanjanBhat - You should update your question with more information then (i.e updated code source) – Sayse Jul 12 '13 at 06:58
  • ` LinkLabel[] flg = new LinkLabel[10];` will create an array with all has null, `foreach (string s in flatestgames) { flg[i] = new LinkLabel(); flg[i].Text = s;` – Satish Bejgum Jul 12 '13 at 07:09
0

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.

Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88