2015-08-06 3 views
0

У меня есть сетка с несколькими столбцами. Я упомянул условие, как будто значение ячейки столбца Сумма < 0 затем измените цвет текста этой строки на серый. Теперь в моей колонке встроен «DataGridViewComboBox». Теперь, когда условие < 0 выполнено, текст всех других столбцов из этой строки становится серым, за исключением этого столбца «DataGridViewComboBox».Установите цвет текста Combobox, встроенный в ячейку datagridview

Я хотел бы знать, как установить цвет выделенного текста Combobox на серый?

Private Function GetComboBoxColumn_Category() As DataGridViewComboBoxColumn 
    Dim ColCombo As New DataGridViewComboBoxColumn 
    Try 
     Using Connection = GetConnection() 
      da = New SqlDataAdapter("SELECT hKey 'iCategory', sCategory FROM tbl_CategoryList WHERE IsObsolete = 0", Connection) 
      dt = New DataTable 
      da.Fill(dt) 
     End Using 
     ColCombo.DataPropertyName = "iCategory" 
     ColCombo.HeaderText = "Category" 
     ColCombo.Name = "iCategory" 
     ColCombo.DataSource = dt 
     ColCombo.ValueMember = "iCategory" 
     ColCombo.DisplayMember = "sCategory" 
     ColCombo.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox 
    Catch ex As Exception 
     ImpensaAlert(ex.Message, MsgBoxStyle.Critical) 
    End Try 

    Return ColCombo 
End Function '1 

Private Sub PopulateExpenditureDetailGrid() 
    Dim TextBoxCell As DataGridViewTextBoxCell 
    Dim strSQL As String = "" 
    Dim dc_Category As DataGridViewComboBoxColumn 
    Dim dc_DelChk As New DataGridViewCheckBoxColumn 

    Try 
     DataGridExpDet.DataSource = Nothing 
     'DataGridExpDet.Columns.Clear() 

     Label15.Text = "Getting Detail Records..." 
     Application.DoEvents() 

     StrClosedYrs = BuildOpenOrClosedYrsStr(1) 'List Of Closed Years 
     dc_Category = GetComboBoxColumn_Category() 
     DataGridExpDet.Columns.Add(dc_Category) 


Private Sub DataGridExpDet_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridExpDet.CellLeave 


    If DataGridExpDet.CurrentCell.ColumnIndex = DataGridExpDet.Columns("Amount").Index And Not String.IsNullOrEmpty(DataGridExpDet(DataGridExpDet.CurrentCell.ColumnIndex, DataGridExpDet.CurrentCell.RowIndex).EditedFormattedValue) Then 
     If DataGridExpDet(DataGridExpDet.CurrentCell.ColumnIndex, DataGridExpDet.CurrentCell.RowIndex).EditedFormattedValue < 0 Then 
      DataGridExpDet.Rows(DataGridExpDet.CurrentCell.RowIndex).DefaultCellStyle.ForeColor = Color.Gray 
     End If 
    End If 
End Sub 

Любая помощь была бы принята с благодарностью.

ответ

0

Обычно, чтобы изменить цвет текста изменить .forecolor

ComboBox1.ForeColor = Color.Gray 

изменит цвет всего текста, расположенного в ComboBox.

Тем не менее, я не думаю, что эти комбинированные поля datagridview имеют эту опцию по умолчанию.

Всякий раз, когда я выполняю обычную работу, я обычно использую RadComboBox. У них есть множество вариантов настройки, которые позволят вам выполнить все, что вам нужно.

редактировать

Ах ха, нашел! - Здесь вы go

Очевидно, вы редактируете его, как обычное поле со списком.

+0

@Nefarri: Теперь приложение полностью разработано не было бы выбор, чтобы обратиться к какому-либо контролю третьей стороны. Я думаю, что могу получить свойство forecolor combobox, как только смогу получить элемент управления, встроенный в ячейку DGV. Просто не знаю, как получить элемент управления, встроенный в ячейку DGV. Что-то вроде DatagridView1. («Категория», RowIndex) .control.forecolor = серый должен работать. – Swad

0

У вас есть два варианта. Один из них прост, а другой задействован.

  1. Дайте колонке Flat стиль. Это изменит внешний вид ComboBox. Но если вы в порядке с этим, то это простой подход. Просто добавьте следующую строку в DataGridViewComboBoxColumn создания:

    ColCombo.FlatStyle = FlatStyle.Flat 
    
  2. вручную рисовать ComboBox текст в правильный цвет. Для этого в дополнение к вашему коду обработайте события DataGridView.CellPainting и DataGridView.EditingControlShowing. Этот метод длиннее, но если вы хотите сохранить внешний вид ComboBox, тогда этот параметр должен работать хорошо.

    ' If the cell is a ComboBox cell: Grab the row ForeColor, 
    ' Paint the cell as usual minus the text, then manually 
    ' Paint the text in the correct color. 
    ' This displays the cell text in the correct color when the cell is not in edit mode. 
    Private Sub DataGridExpDet_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridExpDet.CellPainting 
        If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then 
         If TypeOf DataGridExpDet.Rows(e.RowIndex).Cells(e.ColumnIndex) Is DataGridViewComboBoxCell Then 
          Dim cell As DataGridViewComboBoxCell = DataGridExpDet.Rows(e.RowIndex).Cells(e.ColumnIndex) 
          Dim row As DataGridViewRow = DataGridExpDet.Rows(e.RowIndex) 
          Dim color As Color = If(row.DefaultCellStyle.ForeColor.Name = "0", color.Black, row.DefaultCellStyle.ForeColor) 
    
          Using brush = New SolidBrush(color) 
           Using format = New StringFormat() 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.Background) 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.Border) 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentBackground) 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.ErrorIcon) 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.Focus) 
            e.Paint(e.ClipBounds, DataGridViewPaintParts.SelectionBackground) 
    
            'Don't do the following one - that's what we're overriding. 
            'e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentForeground) 
    
            format.LineAlignment = StringAlignment.Center 
    
            e.Graphics.DrawString(cell.FormattedValue, e.CellStyle.Font, brush, e.CellBounds, format) 
            e.Handled = True 
           End Using 
          End Using 
         End If 
        End If 
    End Sub 
    
    ' Handle the ComboBox control's DrawItem event when showing. 
    ' This draws the selected item and item options' texts in the correct color when in edit mode. 
    Private Sub DataGridExpDet_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridExpDet.EditingControlShowing 
        If TypeOf e.Control Is ComboBox Then 
         Dim cb As ComboBox = TryCast(e.Control, ComboBox) 
         cb.DrawMode = DrawMode.OwnerDrawFixed 
    
         RemoveHandler cb.DrawItem, AddressOf GridComboBox_DrawItem 
         AddHandler cb.DrawItem, AddressOf GridComboBox_DrawItem 
        End If 
    End Sub 
    
    ' Draw the background and focus as normal, then manually 
    ' draw the text values from the indexed datasource row of the 
    ' corresponding DisplayValue column. 
    Private Sub GridComboBox_DrawItem(sender As Object, e As DrawItemEventArgs) 
        e.DrawBackground() 
        e.DrawFocusRectangle() 
    
        Dim cb As ComboBox = TryCast(sender, ComboBox) 
        Dim dt As DataTable = TryCast(cb.DataSource, DataTable) 
    
        Using brush = New SolidBrush(cb.ForeColor) 
         e.Graphics.DrawString(dt.Rows(e.Index).Item("sCategory"), e.Font, brush, e.Bounds) 
        End Using 
    End Sub 
    
+0

Спасибо за ваше решение. Я попробую решение. – Swad

Смежные вопросы