【问题标题】:I am creating an application in windows form我在 Windows 窗体中创建一个应用程序
【发布时间】:2023-02-10 20:08:28
【问题描述】:

我想通过循环添加标签

`private void CourseOutcomes_Load(object sender, EventArgs e)
        {
            studentDetails dets = new studentDetails();
            dets.ShowDialog();
            name=dets.CourseName;
            labelCourseName.Text = name;
            string id = dets.CourseValue;
            SqlDataReader sdr = bznessLogic.GetQuestions(id);
            List<Label> lbl = new List<Label>();
            int count = 0;
            while (sdr.Read()) 
            {
                MessageBox.Show("s");

                lbl[count] = new Label();
                lbl[count].Text = sdr[0].ToString();
                this.Controls.Add(lbl[count]);
                count++;
            }
            sdr.Close();
        }`

但它一直报错 '索引超出范围。

我应该以不同的方式初始化它还是..

【问题讨论】:

  • 开始时索引 0 处没有标签。您必须创建它并将其添加到列表中。

标签: windows-forms-designer


【解决方案1】:

所以事实证明我只需要正确地初始化它,这是我所期望的,菜鸟错误,但我们到了。

private void CourseOutcomes_Load(object sender, EventArgs e)
        {
            studentDetails dets = new studentDetails();
            dets.ShowDialog();
            name=dets.CourseName;
            labelCourseName.Text = name;
            string id = dets.CourseValue;
            SqlDataReader sdr = bznessLogic.GetQuestions(id);
            List<Label> lbl = new List<Label>();
            int count = 0;
            while (sdr.Read()) 
            {
                MessageBox.Show("s");
                lbl.Add(new Label() { Name="lbl"+count});
                lbl[count].Text = sdr[0].ToString();
                this.Controls.Add(lbl[count]);
                count++;
            }
            sdr.Close();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多