尝试使用事件处理程序winform从DataGridView读取时出错



我有一个winform,它有一个通过数据集应用数据的网格视图。当数据绑定时,它会调用SelectionChanged事件处理程序。我对此进行了研究,并通过添加if子句来查看DGV是否有焦点(我发现的所有其他解决方案都不起作用),找到了解决问题的方法。这部分正在按计划工作。当我遍历程序时,事件处理程序在绑定数据时会尝试遍历代码3次。if子句阻止它到达代码。我的问题是,在数据绑定后,我在DGV中选择了一行,然后事件处理程序抛出"在mscorlib.dll中发生了类型为System.ArgumentOutOfRangeException的未处理异常"。在遍历代码时,DGV将正确的行索引返回到我的"int row"变量,但是我用来获取行/单元格信息的代码在将其应用于"loadtableID"变量之前抛出了错误。我需要帮助。您可以忽略顶部的第二个DGV。它获取所选行的信息并获取另一个DB表信息。此外,如果有帮助的话,我没有将数据源应用于程序,也没有为返回的每个单独的数据集创建数据集,我在返回数据时使用系统的通用数据集。

     private void gvMainSelectResults_SelectionChanged(object sender, EventArgs e)
    {
        if (gvMainSelectResults.Focused)
        {
            gvMainArchiveResults.DataSource = null;  //second DGV that is populated later and everytime is cleared with a new selection
            loadTableID = 0;
            orgID = 0;
            dbFileName = "";
            sourceType = "";
            int row = gvMainSelectResults.CurrentCell.RowIndex;
            loadTableID = Convert.ToInt32(gvMainSelectResults.SelectedRows[row].Cells["LoadTableID"].Value);  //this is where I get the error, even if the "int row" has the correct index number
            orgID = Convert.ToInt32(gvMainSelectResults.SelectedRows[row].Cells["OrganizationID"].Value);
            dbFileName = Convert.ToString(gvMainSelectResults.SelectedRows[row].Cells["FileName"].Value);
            sourceType = Convert.ToString(gvMainSelectResults.SelectedRows[row].Cells["SourceType"].Value);
            more code here...

您正在使用RowIndex值从SelectedRows集合中获取文本
但这个集合只包含

获取用户选择的行的集合。

这意味着集合只包含网格中存在的行的子集。当RowIndex为2并且SelectedRows集合中只有一行时,会得到OutOfRange异常。

对于RowIndex值,您应该引用Rows集合,而不是

loadTableID = Convert.ToInt32(gvMainSelectResults.Rows[row].Cells["LoadTableID"].Value);
orgID = Convert.ToInt32(gvMainSelectResults.Rows[row].Cells["OrganizationID"].Value);
dbFileName = Convert.ToString(gvMainSelectResults.Rows[row].Cells["FileName"].Value);
sourceType = Convert.ToString(gvMainSelectResults.Rows[row].Cells["SourceType"].Value);

最新更新