InvalidArgument =' 1'的值不适用于' index'

时间:2015-06-10 19:14:51

标签: c# ms-access

我的C#应用​​程序中有一个与MDB访问数据库交互的错误。

错误是:

  

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 - 编号 - BillDate - 供应商 - 总计 - 注意

1 个答案:

答案 0 :(得分:0)

我可能已经找到了这个问题。

如果第一次围绕'if(Date1&gt; = 0&amp;&amp; Date2&lt; = 0)'statemant计算为false,则i索引仍然会递增。然后在第二次迭代中,if语句可能会评估为true,然后你的索引将逐个进行,因为ListView中只有一个Item,但是你尝试使用listView1.Items [1],而不是listView1.Items [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++;
}