You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Forms循环添加Label报‘索引超出范围’,求解决方案

问题解决:WinForms循环添加Label控件报“Index was out of range”错误

你遇到的Index was out of range错误,核心原因是初始化的List<Label>是空集合,直接通过索引lbl[count]访问不存在的元素导致的。List<T>在创建后没有元素时,不能直接用索引赋值,必须先向集合中添加元素。

方案一:修正List的使用方式

把直接索引赋值改成Add方法添加新Label,同时建议设置Label位置避免重叠:

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 yPos = 20; // 起始垂直位置
    
    while (sdr.Read())
    {
        Label newLabel = new Label();
        newLabel.Text = sdr[0].ToString();
        newLabel.Location = new Point(20, yPos); // 设置位置,避免重叠
        this.Controls.Add(newLabel);
        lbl.Add(newLabel); // 将创建的Label添加到List中
        yPos += 30; // 每次下移30像素
    }
    sdr.Close();
}

方案二:无需保存Label列表时的简化写法

如果后续不需要操作这些Label集合,可以直接创建并添加到控件,省去List:

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);
    int yPos = 20;
    
    while (sdr.Read())
    {
        Label newLabel = new Label();
        newLabel.Text = sdr[0].ToString();
        newLabel.Location = new Point(20, yPos);
        this.Controls.Add(newLabel);
        yPos += 30;
    }
    sdr.Close();
}

额外优化建议

  • 使用using语句包裹SqlDataReader,确保数据库资源自动释放,无需手动调用Close():
using(SqlDataReader sdr = bznessLogic.GetQuestions(id))
{
    int yPos = 20;
    while (sdr.Read())
    {
        Label newLabel = new Label();
        newLabel.Text = sdr[0].ToString();
        newLabel.Location = new Point(20, yPos);
        this.Controls.Add(newLabel);
        yPos += 30;
    }
}

内容的提问来源于stack exchange,提问作者Aisha AQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:20:51