日期:2014-05-17  浏览次数:21510 次

C#winform中运用dataGridView出现“索引超出范围。必须为非负值并小于集合大小。”
C# code

int n = 0;
                string sqlsign = "select count(*) from HouseHold,DetailAccount where HouseHold.HouseID = DetailAccount.HouseID and HouseHold.Area = '" + comboBox1.Text.ToString().Trim() + "'";
                string sql = "select * from HouseHold,DetailAccount where HouseHold.HouseID = DetailAccount.HouseID and HouseHold.Area = '" + comboBox1.Text.ToString().Trim() + "'";
                OleDbConnection conn = dbObj.GetConnection();
                OleDbCommand comm = new OleDbCommand(sql, conn);
                OleDbCommand commsign = new OleDbCommand(sqlsign, conn);
                    conn.Open();
                    n = (int)commsign.ExecuteScalar();
                        comm.ExecuteNonQuery();
                        OleDbDataAdapter da = new OleDbDataAdapter(comm);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "HouseHold");
                        for (int i = 0; i < n; i++)
                        {
                            dataGridView1.Rows[i].Cells["index_no"].Value = i+1;
                            dataGridView1.Rows[i].Cells["HouseID"].Value = ds.Tables["HouseHold"].Rows[i][0].ToString();
                            dataGridView1.Rows[i].Cells["theName"].Value = ds.Tables["HouseHold"].Rows[i][8].ToString();
                            dataGridView1.Rows[i].Cells["theOwner"].Value = ds.Tables["HouseHold"].Rows[i][2].ToString();
                            dataGridView1.Rows[i].Cells["Category"].Value = ds.Tables["HouseHold"].Rows[i][3].ToString();
                            dataGridView1.Rows[i].Cells["Area"].Value = ds.Tables["HouseHold"].Rows[i][5].ToString();
                            dataGridView1.Rows[i].Cells["Address"].Value = ds.Tables["HouseHold"].Rows[i][4].ToString();
   
                       }




一直出现“索引超出范围。必须为非负值并小于集合大小。参数名为index。”dataGridView1的列是我自定义出来的,没有采用数据绑定,折腾了一天没折腾出来是啥原因,求助各位大虾啊!!

------解决方案--------------------
访问越界,对[]的地方好好调试,还有Rows[i]是否越界,你有那么多行吗
------解决方案--------------------
For 循环超出了你SQL导出来的列数
你可以
C# code

messagebox.show( dataGridView1.Rows.Count.ToString());

------解决方案--------------------
先要添加行,才能对每个得进行操作
dataGridView1.Rows.Add()