簡體   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