Generate XML Error: Additional information: Index was out of range. Must be non-negative and less than the size of the collection

Generate XML Error: Additional information: Index was out of range. Must be non-negative and less than the size of the collection

所以我尝试通过使用 SAX 单击 windows 表单中的按钮从我的数据库生成发票 xml 文档,但是我一直收到错误 "Index was out of range. Must be non-negative and less than the size of the collection." 我不确定出了什么问题。以下是有问题的代码:[1]: https://i.stack.imgur.com/UsJdG.png

var productID = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
var productName = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();

 wrt.WriteElementString("ItemID",productID);
 wrt.WriteElementString("ItemName", productName);

IndexOutOfRangeException occurs when you are trying to access elements that are not within the range or count of the array in question. For example, if your array has 3 elements at all, accessing the fourth item will always fail.

关于您的问题,有几种情况可能会导致此类错误。

  1. 在您未选择网格中的任何行时尝试访问 selectedRows。在继续之前确认用户已选择网格中的项目。

    1. 选择一行时,可能不知道该选定行的结果单元格,因此这种方法可能行不通

我会提出这个解决方案。

if(dataGridView1.SelectedRows.Length > 0)
    {
        //get all selected rows
        var rows = dataGridView1.SelectedRows;

        if(rows.Length > 0)
        {
            for (int i = 0; i < rows.Length; i++)
            {
                //get cells in individual columns
                var cells = rows[i].Cells;

                if(cells.Length > 0)
                {
                    //productId in cell 1
                    var productId = cells[0].Value.ToString();

                    //product name in cell 2
                    var productName = cells[1].Value.ToString();

                    wrt.WriteElementString("ItemID",productId);
                    wrt.WriteElementString("ItemName", productName);
                }
            }
        }
    }

希望对您有所帮助。