我的代码中出现此错误: InvalidArgument =' 3'的值对于' index'无效。参数名称:索引, 当我想填写我的listview的一部分时! 这是我的代码:
MySqlCommand cmd = new MySqlCommand("select acc_Id,acc_Name,acc_Place from accounts where archived=0 and cus_Sup=" + 0 , objConn);
MySqlDataReader dataReader = cmd.ExecuteReader();
int i = 0;
while (dataReader.Read())
{
if (i % 2 == 0)
listView2.Items.Add(dataReader.GetValue(0).ToString()).BackColor = Color.Lavender;
else
listView2.Items.Add(dataReader.GetValue(0).ToString());
listView2.Items[i].SubItems.Add(dataReader.GetString(1).ToString());
listView2.Items[i].SubItems.Add((dataReader.IsDBNull(2) ? "No place added" : dataReader.GetString(2)));
//------------------------------------I meant here !
listView2.Items[i].SubItems.Add("0");
listView2.Items[i].SubItems.Add("0");
listView2.Items[i].SubItems.Add("0");
}
dataReader.Close();
//-------------load bills
for (int x = 0; x < listView2.Items.Count; x++)
{
cmd = new MySqlCommand("select c.acc_Id,a.bill_Number,a.bill_Date,c.acc_Name,Sum( (b.de_Quantity * b.de_Price) - ((b.de_Quantity * b.de_Price)*b.de_DisRate/100) ),a.bill_TaxRate,a.bill_DisRate,a.bill_Note,c.acc_Place from (accounts c right JOIN bills a on c.acc_Id = a.bill_From) LEFT JOIN bill_Details b on a.bill_Id = b.bill_Id where c.acc_Id = " + listView2.Items[x].SubItems[0].Text + " group by a.bill_Id,a.bill_Number,a.bill_Date,c.acc_Name,a.bill_TaxRate,a.bill_DisRate,a.bill_Note,c.acc_Place ", objConn);
dataReader = cmd.ExecuteReader();
decimal totalSum = 0, summBills = 0;
i = 0;
while (dataReader.Read())
{
totalSum = decimal.Parse(dataReader.IsDBNull(4) ? "0" : dataReader.GetDecimal(4).ToString("n2"));
totalSum -= (totalSum * decimal.Parse(dataReader.IsDBNull(6) ? "0" : dataReader.GetDecimal(6).ToString("n2")) / 100);
totalSum += (totalSum * decimal.Parse(dataReader.IsDBNull(5) ? "0" : dataReader.GetDecimal(5).ToString("n2")) / 100);
summBills += totalSum;
i++;
}
//MessageBox.Show(dataReader.GetValue(0).ToString()+" "+summBills.ToString());
listView2.Items[x].SubItems[3].Text = summBills.ToString("n2");// the error here !
dataReader.Close();
}
它只打印第一张唱片的价值! ,当它移动到第二个时出现错误!
答案 0 :(得分:1)
您已为每个ListView项添加了3个子项。它们将是Items [x] .SubItems [0]到SubItems [2]。您需要添加4个SubItem才能使用SubItem [3]。
编辑:
当您在顶部循环中添加项目时,您不会递增i - 您需要将顶部循环更改为:
int i = 0;
while (dataReader.Read())
{
if (i % 2 == 0)
listView2.Items.Add(dataReader.GetValue(0).ToString()).BackColor = Color.Lavender;
else
listView2.Items.Add(dataReader.GetValue(0).ToString());
listView2.Items[i].SubItems.Add(dataReader.GetString(1).ToString());
listView2.Items[i].SubItems.Add((dataReader.IsDBNull(2) ? "No place added" : dataReader.GetString(2)));
//------------------------------------I meant here !
listView2.Items[i].SubItems.Add("0");
listView2.Items[i].SubItems.Add("0");
listView2.Items[i].SubItems.Add("0");
i++;
}
dataReader.Close();
如果没有这个,你每次都会向ListView添加一个新的Item,但每次都会将listItems添加到listView2.Items [0]。这就是为什么第二个失败的原因。 Items [0]有5个子项的多个,其余的没有。