【问题标题】:index was outside the bounds of the array meaning WPF C# [duplicate]索引超出了数组的范围,这意味着 WPF C# [重复]
【发布时间】:2017-04-05 17:39:57
【问题描述】:

我尝试使用此代码在循环中显示数据库中的名称,但这表明错误索引超出了这一行的数组含义 name[j++] = Convert.ToString(reader["CategoryName"]);

代码

 con.Open();
        int count =0;
        int j =0;
        //cmd = new SqlCommand("select * from Category");
        string[] name = new string[count];
        cmd = new SqlCommand("select CategoryName from Category",con);
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            name[j++] = Convert.ToString(reader["CategoryName"]);
        }
        int loc = 37;
        CheckBox[] obj = new CheckBox[count];
        for (int i = 0; i < count; i++)
        {
            obj[i] = new CheckBox();
            obj[i].Location = new System.Drawing.Point(loc, 50);
            obj[i].Size = new System.Drawing.Size(80, 17);
            obj[i].Text = name[i];
            this.Controls.Add(obj[i]);
            loc += 80;

        }
        con.Close();

有什么帮助吗?

【问题讨论】:

  • 您正在初始化您的 name 数组,其大小为 0
  • 你声明 int count = 0; 然后 string[] name = new string[count]; 所以名字的长度是零个字符。然后您访问它并尝试写入该零长度数组。你期望会发生什么?我知道!您将收到一条错误消息,提示 索引超出了数组的范围。我会中奖吗?
  • 你将name初始化为一个大小为0的数组。然后,您尝试访问 大小为 0 的数组的索引,并想知道为什么会出现索引越界异常?也许做一些谷歌搜索,以更好地了解异常是什么,为什么会发生,以及如何解决它。

标签: c# arrays wpf loops indexing


【解决方案1】:

一开始就设置

int count =0;

然后你像这样初始化数组:

new string[count];

您实际上是在创建一个包含零个位置的数组。 然后你循环:

name[j++]

您访问数组中不存在的索引

【讨论】:

    【解决方案2】:

    你设置count = 0 然后你用它创建一个数组

    string[] name = new string[count];
    

    这意味着您的数组长度为 0,您将无法为其分配任何内容。 我建议你把它改成List 这样会容易得多

    List<string> name = new List<string>();
    
    while (reader.Read())
    {
        name.Add(Convert.ToString(reader["CategoryName"]));
    }
    

    【讨论】:

    • 好的,如何在标签中显示该名称?
    • @Super 你可以像访问数组一样通过name[i]访问List。您可以通过count = name.Count; 获取列表中的项目数量
    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 2016-05-12
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2015-11-06
    • 2010-11-17
    相关资源
    最近更新 更多