您好,如果我将(i)值放入itemsWS.getItemInfo(itemLis [i] .ToString()),您将得到“索引超出数组范围”

    object[] itemDetails;
    object[] itemLis = itemsWS.searchItem("", "bread", "all");
    int xs = 35;
    int clefts = 0;

    for (int i = 0; i < itemLis.Length; i++)

    {
        itemDetails = itemsWS.getItemInfo(itemLis[i].ToString());
        Button myButtons = new Button();
        myButtons.Click += delegate
        {

            dataGridView1.ColumnCount = 11;

            dataGridView1.Columns[0].Name = "Item Code";
            dataGridView1.Columns[1].Name = "Description";
            dataGridView1.Columns[2].Name = "Sale Price";
            dataGridView1.Columns[3].Name = "Category";
            dataGridView1.Columns[4].Name = "Type";
            dataGridView1.Columns[5].Name = "Status";
            dataGridView1.Columns[6].Name = "Low Count";
            dataGridView1.Columns[7].Name = "Medium Count";
            dataGridView1.Columns[8].Name = "High Count";
            dataGridView1.Columns[9].Name = "Item Picture";
            dataGridView1.Columns[10].Name = "TEST";

            //here is where i'm getting error if i put i on the []

            itemDetail = itemsWS.getItemInfo(itemLi[i].ToString());

            //

            dataGridView1.Rows.Add(itemDetail);
            MessageBox.Show("data grid displayed!");

        };


        myButtons.Text = itemDetails[1].ToString() + "\n  " + itemDetails[2].ToString();
        myButtons.Top = cleft * 180;
        myButtons.Left = 70;
        myButtons.Location = new Point(xs, clefts);
        myButtons.Size = new Size(100, 60);
        tabPage1.Controls.Add(myButtons);
        xs += 135;

        if (xs >= 537)
        {
            xs = 35;
            clefts += 80;
        }


(这是数据库)

c# - C#索引超出了数组的范围-LMLPHP

问题是如果我将[i]替换为[0]。它将仅显示数据库中的第一个值项目

(如果我将[i]替换为[0],则为GUI)单击任何按钮将重复相同的输出

c# - C#索引超出了数组的范围-LMLPHP

请任何帮助将不胜感激。我正在尝试使用生成的新按钮显示来自MySQL的项目,这些按钮将显示在datagridview上。谢谢

最佳答案

尝试将i的值存储在委托示例内的局部变量中:

myButtons.Click += delegate
{
  …
  int local_i = i;
  itemDetail = itemsWS.getItemInfo(itemLis[local_i].ToString());
  …
}


实际执行委托时,i的值可能超出范围。

更新:
没有看到应用程序中的所有其他代码,很难确定,但是可能是委托执行时itemLis不再包含该索引处的项目。

尝试使用foreach循环,这样,在执行委托时,您将不会从itemLis数组中检索项目。

foreach (var item in itemLis)
{
 itemDetails = itemsWS.getItemInfo(item);
    ....
    myButtons.Click += delegate
         {
         ...
         itemDetail = itemsWS.getItemInfo(item);
         ...
     }
  ...
}

10-08 13:50