2011-08-30 148 views
1

我有一個DataGridview有幾列,其中一列是DataGridViewComboBoxColumn。若要動態更改DataGridViewComboBoxCell顏色(樣式)

這種情況是,當用戶從組合框中選擇一些值(選擇索引> 0)時,所選單元格的整行將顯示爲白色。如果用戶選擇組合框的空值(選定索引爲0),則整行將以黃色顯示,並且此組合框單元應顯示爲紅色。

我能夠實現顯示除了組合框以外的黃色整行。

private void grdCurve_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
     { 
      //for datatype column 
      if (grdCurve.CurrentCell.ColumnIndex == DATATYPE_COLUMN_INDEX) 
      { 
       // Check box column 
       ComboBox comboBox = e.Control as ComboBox; 
       comboBox.SelectedIndexChanged -= new EventHandler(comboBox_SelectedIndexChanged); 
       comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged); 
      } 
     } 

void comboBox_SelectedIndexChanged(object sender, EventArgs e) 
     { 
     if (selectedIndex >= 0) 
      { 
      if (!ValidateMnemonic(mnRow, row)) 
       { 
        MarkInvalidRow(row); 
       } 
       else 
       { 
        MarkValidRow(row); 
       } 
      } 
     } 

private void MarkInvalidRow(DataGridViewRow row) 
     { 
      DataGridViewCellStyle style = new DataGridViewCellStyle(); 
      if (m_InvalidRowTable.Count > 0) 
      { 
       if (m_InvalidRowTable.ContainsKey(row.Index)) 
       { 
        int col = Convert.ToInt32(m_InvalidRowTable[row.Index]); 
        DataGridViewCell cell = row.Cells[col]; 
        MarkInvalidRowColor(row); 
        style.BackColor = Color.Red; 
        style.SelectionBackColor = Color.Red; 
        cell.Style = style; 
        if (grdCurve.CurrentCell is DataGridViewComboBoxCell) 
        {       
         grdCurve.CurrentCell.Style = style; 
        } 
       } 
       else 
       { 
        MarkInvalidRowColor(row); 
       } 
      } 
      else 
      { 
       MarkInvalidRowColor(row); 
      } 

      m_InvalidRowTable.Remove(row.Index); 
     } 

private void grdCurve_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
     { 
      //do nothing 
     } 

private void grdCurve_CurrentCellDirtyStateChanged(object sender, EventArgs e) 
     { 
      if (grdCurve.CurrentCell is DataGridViewCheckBoxCell) 
       grdCurve.CommitEdit(DataGridViewDataErrorContexts.Commit); 

      if (grdCurve.CurrentCell is DataGridViewComboBoxCell && grdCurve.IsCurrentCellDirty) 
       grdCurve.CommitEdit(DataGridViewDataErrorContexts.Commit); 

      grdCurve.EndEdit(); 
     } 

當我將組合框中的項目更改爲空時,我預計組合框將被標記爲紅色。 但是,它顯示爲白色,當我點擊其他一些單元格時,紅色將在組合框單元格中更新。

請幫忙。

感謝, 普拉薩德

回答