【问题标题】:Index out of range exception while inserting elements into a list将元素插入列表时索引超出范围异常
【发布时间】:2014-06-13 06:58:56
【问题描述】:

我不断收到以下错误: “索引超出范围。必须为非负数且小于集合的大小”,同时执行以下代码:

 try
        {
            string connectionstring = "server=localhost;user id=root;database=itemdb;password=root";
            MySqlConnection conn = new MySqlConnection(connectionstring);
            conn.Open();
            MySqlCommand cmd = new MySqlCommand("SELECT item.item_name,location.city,time.month,SUM(unit_sales) FROM sales_fact,time,item,location WHERE(sales_fact.item_key = item.item_key AND sales_fact.location_key = location.location_key AND sales_fact.time_key = time.time_key) GROUP BY item.item_name", conn);
            MySqlDataReader dr = cmd.ExecuteReader();
            int c = 0;
            List<Cube1> cubelist = new List<Cube1>();
            while (dr.Read())
            {
                //i++;
                cubelist[c].itemname = dr.GetValue(0).ToString();
                cubelist[c].city = dr.GetValue(1).ToString();
                cubelist[c].month = dr.GetValue(2).ToString();
                cubelist[c].totalsales = (int)dr.GetValue(3);
                MessageBox.Show(cubelist[0].totalsales.ToString());
                c++;
            }
            dr.Close();
            MySqlDataAdapter da = new MySqlDataAdapter(connectionstring, conn);
            DataSet dt = new DataSet();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

我哪里出错了?

【问题讨论】:

  • 你应该做 cubelist.Add().
  • 最小模式:将//i++;更改为cubelist.Add(new Cube1());

标签: c# .net arraylist


【解决方案1】:

您创建一个新的(空的)List&lt;Cube1&gt;,然后尝试分配给由于列表为空而不存在的元素的属性。您需要使用var cube = new Cube1() 来实例化一个新的Cube1,而不是使用cubelist[c],然后将值分配给它的属性,然后使用cubelist.Add(cube) 将其添加到列表中。

List<Cube1> cubelist = new List<Cube1>();
while (dr.Read())
{
    // Create a new Cube1 instance
    var cube = new Cube1();

    // Set its properties
    cube.itemname = dr.GetValue(0).ToString();
    cube.city = dr.GetValue(1).ToString();
    cube.month = dr.GetValue(2).ToString();
    cube.totalsales = (int)dr.GetValue(3);

    // Add it to the list
    cubelist.Add(cube);

    MessageBox.Show(cube.totalsales.ToString());
}

您根本不需要您的 c 变量。

【讨论】:

    【解决方案2】:

    您的列表是空的,但您正在尝试访问它的元素。您应该首先使用List&lt;T&gt;.Add 方法。在您的代码中:

    new List<Cube1>(100);
    

    100 只指定Capacity,它不是你列表的大小。它用于分配一个指定长度的数组,以避免每次向列表中添加新项目时重新分配。

    cubelist.Add(new Cube());
    cubelist[c].itemname = dr.GetValue(0).ToString();
    cubelist[c].city = dr.GetValue(1).ToString();
    ...
    

    【讨论】:

    • 海报现在改变了它的代码,但不是标题:-)
    • @Steve 是的,你说得对,但仍然存在同样的例外情况。 :) List&lt;T&gt; 的索引器抛出异常,为了获得 nullreference 你应该至少有一个 null 项:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多