【问题标题】:C#: Selecting a row in DataGridView with parametersC#:使用参数在 DataGridView 中选择一行
【发布时间】:2012-08-10 17:29:46
【问题描述】:

我有一个 DataGridView 和一个添加新条目按钮。每次向数据库添加新条目时,我希望程序在 DataGridView 中选择新条目所在的行。单击 Add New Entry 按钮后,将调用以下函数,并将 studentName 和 date 参数传递给该函数。 DataGridView 的名称是 dvgPontengHistory。

但是抛出了异常:

对象引用未设置为对象的实例。

在这一行:

if(r.Cells["student_name"].Value.ToString().Contains(studentName))

下面是代码:

   private void selectRow(string studentName, string date)
    {
        int i = 0;
        foreach (DataGridViewRow r in dgvPontengHistory.Rows)
        {
            if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
            {
                if (r.Cells["date"].Value.ToString().Contains(date))
                {
                    dgvPontengHistory.Rows[i].Selected = true;
                    return;
                }
            }
            i++;
        }
    }

有解决此问题的提示吗?谢谢。

【问题讨论】:

  • 您确定列名正确吗?
  • 当您添加行时,您需要刷新数据源以便选择该列,这就是您找不到它并引发异常的原因。 unlleessssss 你真的输入了错误的列名
  • 捕获异常、调试、放置断点并设置一些监视来检查r.Cells["student_name"]r.Cells["student_name"].Value 的值。
  • @MutuYolbulan - 这不是问题,找不到它只会导致循环结束。

标签: c# datagridview


【解决方案1】:

结果集中的行中可能有 student_name 为 null 的情况。这会导致 ToString() 失败。

我的猜测是您的更新语句将 null 放入您的表中。

这是你的测试方法:

(在投掷线上设置断点)。

  private void selectRow(string studentName, string date)
    {
        int i = 0;
        foreach (DataGridViewRow r in dgvPontengHistory.Rows)
        {
            if (r.Cells["student_name"] == null) { throw("can't find cell"); }
            if(r.Cells["student_name"].Value == null) { throw("cell has no value"); }
            if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
            {
                if (r.Cells["date"].Value.ToString().Contains(date))
                {
                    dgvPontengHistory.Rows[i].Selected = true;
                    return;
                }
            }
            i++;
        }
    }

【讨论】:

    【解决方案2】:
    private void selectRow(string studentName, string date)
    {
        int i = 0;
        foreach (DataGridViewRow r in dgvPontengHistory.Rows)
        {
            if(r.Cells["student_name"].Value == null) return;
            if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
            {
                if (r.Cells["date"].Value.ToString().Contains(date))
                {
                    dgvPontengHistory.Rows[i].Selected = true;
                    return;
                }
            }
            i++;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多