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

时间:2016-03-26 14:44:44

标签: winforms exception datagridview eventhandler

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

     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...

1 个答案:

答案 0 :(得分:0)

您正在使用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);