在C#中使用foreach动态创建链接标签 [英] Dynamically creating Link Labels using foreach in c#

查看:62
本文介绍了在C#中使用foreach动态创建链接标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

这篇关于在C#中使用foreach动态创建链接标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆