InvalidArgument= 1'对'索引'无效
本文关键字:索引 无效 InvalidArgument | 更新日期: 2023-09-27 17:54:56
我的c#应用程序与MDB访问DB交互时出现错误。
错误是:
我代码:InvalidArgument= '1'的值对'index'无效。
objConn.Open();
listView1.Items.Clear();
OleDbCommand cmd = new OleDbCommand("select a.bill_Id,a.bill_Number,a.bill_Date,c.sup_Name,Sum(b.de_NetPrice),a.bill_Note from (suppliers c right JOIN bills a on c.sup_Id = a.bill_From) LEFT JOIN bill_Details b on a.bill_Id = b.bill_Id where a.bill_Id like '%" + txbSearch.Text + "%' or a.bill_Number like '%" + txbSearch.Text + "%' or c.sup_Name like '%" + txbSearch.Text + "%' or a.bill_Note like '%" + txbSearch.Text + "%' group by a.bill_Id,a.bill_Number,a.bill_Date,c.sup_Name,a.bill_Note order by a.bill_Date desc", objConn);
OleDbDataReader dataReader = cmd.ExecuteReader();
int i = 0;
while (dataReader.Read())
{
DateTime dt0 = DateTime.Parse(dataReader.GetValue(2).ToString());
int Date1 = DateTime.Compare(DateTime.Parse(dt0.ToShortDateString()), DateTime.Parse(txbFrom.Value.ToShortDateString()));
int Date2 = DateTime.Compare(DateTime.Parse(dt0.ToShortDateString()), DateTime.Parse(txbTo.Value.ToShortDateString()));
if (Date1 >= 0 && Date2 <= 0)
{
listView1.Items.Add(dataReader.GetValue(0).ToString());
// The error happens on the following line
listView1.Items[i].SubItems.Add(dataReader.GetValue(1).ToString());
listView1.Items[i].SubItems.Add(dt0.ToShortDateString());
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(3) ? "0" : dataReader.GetString(3));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(4) ? "0" : dataReader.GetDouble(4).ToString("n2"));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(5) ? "-" : dataReader.GetString(5));
}
i++;
}
objConn.Close();
listview有这些列:ID—编号—账单日期—供应商—总计—备注
我可能找到问题了。
If (Date1>= 0 &&如果Date2 <= 0)'语句的计算结果为false,则i索引仍将被加1。然后在第二次迭代中if语句可能求值为true,然后你的索引会偏离1,因为在ListView中只有一个Item,但你尝试使用listView1。Items[1],而不是listView1。条目[0],这将是正确的。
解决方案是将代码更改为:if (Date1 >= 0 && Date2 <= 0)
{
listView1.Items.Add(dataReader.GetValue(0).ToString());
listView1.Items[i].SubItems.Add(dataReader.GetValue(1).ToString());// The error appears on this line
listView1.Items[i].SubItems.Add(dt0.ToShortDateString());
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(3) ? "0" : dataReader.GetString(3));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(4) ? "0" : dataReader.GetDouble(4).ToString("n2"));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(5) ? "-" : dataReader.GetString(5));
i++;
}