2017-10-14 86 views
-1

我想做一些類似的事情,如果從下拉框中有選擇,它應該對Datagridview行進行顏色更改。不能隱式地將類型字符串轉換爲System.Windows.Forms.Datagridviewcell c#

我已經使用開關盒,沒有改變任何東西,因此我想用另一種方法。代碼如下所示

private void RowsColor() 
{ 
    try 
    { 
     for (int i = 0; i < dataGridView1.Rows.Count; i++) 
     { 
      if (dataGridView1 != null) 
      { 
       if (dataGridView1.Rows != null) 
       { 
        if (dataGridView1.Rows[i].Cells != null) 
        { 
         if (dataGridView1.Rows[i].Cells[11] != null) 
         { 
          //string val = dataGridView1.Rows[i].Cells[11].Value.ToString(); 
          var val = dataGridView1.Rows[i].Cells[11]; 
          if (val = "Confirm Appointment") 
          { 
           dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red; 
          } 
          else if (val = "Reschedule") 
          { 
           dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 

現在我得到這樣的事情作爲一個錯誤

不能字符串類型隱式轉換爲 System.Windows.Forms.Datagridviewcell

這個新,我錯過了什麼?

+0

在哪一行? – farbiondriven

+0

@farbiondriven if(val =「Confirm Appointment」)if else(val =「Reschedule」) – Thomas

+0

@Thomas'val'是符合時間確定的'Datagridviewcell'類型,但您將其與字符串 – Niladri

回答

0

Decomment

string val = ""; 
try{ 
    val = dataGridView1.Rows[i].Cells[11].Value.ToString(); 
    } 
catch(NullReferenceException ex){ 
    val = "Not yet set" 
} 

if (val.Equals("Confirm Appointment")) 
    { 
     dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red; 
    } 
else if (val.Equals("Reschedule")) 
    { 
     dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; 
    } 
+0

會拋出字符串異常val = dataGridView1.Rows [i] .Cells [1] .Cells [11] .Value.ToString 11] .Value.ToString(); – Thomas

+0

哪個例外? – farbiondriven

+0

NullreferenceException對象引用未設置爲對象的實例,整天都在與它對抗! – Thomas

相關問題