Установить цвет шрифта элементов в DataGridViewComboBoxCell - PullRequest
0 голосов
/ 22 февраля 2012

Как я могу установить цвет шрифта для разных элементов в DataGridViewComboBoxCell? Например, если у меня есть 10 предметов, как я могу сделать предметы 3 и 5 красными, а остальные оставить черными?

РЕДАКТИРОВАТЬ: Это для приложения winform, и DataGridViewComboBox не привязан к данным

edit2: Может быть, я мог бы сделать это здесь в editcontrolshow?

   private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
   {
            if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == "MyCombo")
            {

                DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.CurrentCell;

                for (int i = 0; i < comboCell.Items.Count; ++i)
                {
                    string contract = comboCell.Items[i].ToString();
                    if (contract.ToUpper().Contains("NO"))
                    {
                        // can I set this item have a red font color???
                    }

                }
}

Ответы [ 2 ]

1 голос
/ 22 февраля 2012

для строк, сделанных ниже - подключите OnRowDataBound событие, затем выполните вещи

ASPX (Сетка):

    <asp:.... OnRowDataBound="RowDataBound"..../>

Код позади:

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex == -1)
        {
            return;
        }

        if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
             e.Row.BackColor=Color.Red;   
        }
    }

ДЛЯ WinForms:

hook the **DataBindingComplete** event and do stuff in it:

     private void dataGridView1_DataBindingComplete(object sender, 
                       DataGridViewBindingCompleteEventArgs e)
    {
        if (e.ListChangedType != ListChangedType.ItemDeleted)
        {
            DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
            red.BackColor=Color.Red;

            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells["FollowedUp"].Value.ToString()
                       .ToUpper().Contains("NO"))
                {
                    r.DefaultCellStyle = red;
                }
            }
        }
    }
0 голосов
/ 15 мая 2013

Вам необходимо нарисовать элементы ComboBox вручную. Попробуйте выполнить следующее (на основе этой записи MSDN ):

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    // Note this assumes there is only one ComboBox column in the grid!
    var comboBox = e.Control as ComboBox;
    if (comboBox == null)
        return;

    comboBox.DrawMode = DrawMode.OwnerDrawFixed;
    comboBox.DrawItem -= DrawGridComboBoxItem;
    comboBox.DrawItem += DrawGridComboBoxItem;
}

private void DrawGridComboBoxItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();

    if (e.Index != -1)
    {
        // Determine which foreground color to use
        var itemValue = actionsColumn.Items[e.Index] as string;
        bool isNo = String.Equals("no", itemValue, StringComparison.CurrentCultureIgnoreCase);
        Color color = isNo ? Color.Red : e.ForeColor;

        using (var brush = new SolidBrush(color))
            e.Graphics.DrawString(itemValue, e.Font, brush, e.Bounds);
    }

    e.DrawFocusRectangle();
}
...