在列表中插入元素时出现索引超出范围的异常
本文关键字:索引 范围 异常 插入 元素 列表 | 更新日期: 2023-09-27 18:00:29
我一直收到以下错误:在执行以下代码时,"索引超出范围。必须是非负数并且小于集合的大小":
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);
}
我哪里错了?
您的列表是空的,但您正在尝试访问它的元素。您应该首先使用List<T>.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();
...
创建一个新的(空的)List<Cube1>
,然后尝试分配给由于列表为空而不存在的元素的属性。您不需要使用cubelist[c]
,而是需要执行var cube = new Cube1()
来实例化新的Cube1
,然后将值分配给其属性,然后使用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
变量。