繁体   English   中英

C#:在带参数的DataGridView中选择一行

[英]C#: Selecting a row in DataGridView with parameters

我有一个DataGridView和一个Add New Entry按钮。 每次将新条目添加到数据库时,我都希望程序在DataGridView中选择新条目的行。 单击“添加新条目”按钮后,将调用以下函数,并将studentName和日期参数传递给该函数。 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++; } } 

解决此问题的任何技巧? 谢谢。

在结果集中的某些行中,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++;
        }
    }
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++;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM