Dynamically creating Link Labels using foreach in c#

≯℡__Kan透↙ 提交于 2019-12-11 14:57:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!