2017-07-02 83 views
0

我有以下代碼:如何比較單元格的值與字符串變量?

string findID = pacients.findByUniqueCode(code); 

    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
    if ((string)row.Cells["idDataGridViewTextBoxColumn"].Value == findID) 
    { 

    } 
} 

我行得到一個錯誤:

if ((string)row.Cells["idDataGridViewTextBoxColumn"].Value == findID) 

它不能轉換row.Cells字符串。如何解決它?

+0

'Convert.ToString(row.Cells [「idDataGridViewTextBoxColumn」]。Value)'' –

回答

1

比較字符串,無論你的價值觀必須是一個字符串,其東北角你的情況不是個例!

所以,你必須做什麼去修正這個是轉換你的row.Cells["idDataGridViewTextBoxColumn"].Value爲一個字符串,以及如何做到這一點,取決於你,有幾種方法,但我會在這裏提到兩種最常見的,

你可以通過建立.ToString()方法,或者你可能使用也建立Convert.ToString()方法做到這一點,是你,你會選擇,讓你的代碼可能是這樣的:

if (Convert.ToString(row.Cells["idDataGridViewTextBoxColumn"].Value) == findID) 
{ 
    .... 
} 

if ((row.Cells["idDataGridViewTextBoxColumn"].Value).ToString() == findID) 
{ 
    ..... 
} 

應用上述任何情況應該可以解決您的問題。

謝謝

0

爲什麼不使用ToString?

if (row.Cells["idDataGridViewTextBoxColumn"].Value.ToString() == findID)