Changing the format of a ComboBox item

前端 未结 5 1886
挽巷
挽巷 2021-01-02 04:33

Is it possible to format a ComboBox item in C#? For example, how would I make an item bold, change the color of its text, etc.?

5条回答
  •  星月不相逢
    2021-01-02 05:28

    Just to add to the answer supplied by Dan, don't forget that if you have bound the list to a Datasource, rather than just having a ComboBox with plain strings, you won't be able to redraw the entry by using combo.Items[e.Index].ToString().

    If for example, you've bound the ComboBox to a DataTable, and try to use the code in Dan's answer, you'll just end up with a ComboBox containing System.Data.DataRowView, as each item in the list isn't a string, it's a DataRowView.

    The code in this case would be something like the following:

     private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
                {
                    if (e.Index == -1)
                        return;
                    ComboBox combo = ((ComboBox)sender);
    
                    using (SolidBrush brush = new SolidBrush(e.ForeColor))
                    {
                        Font font = e.Font;
                        DataRowView item = (DataRowView)combo.Items[e.Index];
    
                        if (/*Condition Specifying That Text Must Be Bold*/) {
                            font = new System.Drawing.Font(font, FontStyle.Bold);
                        }
                        else {
                            font = new System.Drawing.Font(font, FontStyle.Regular);
                        }                    
    
                        e.DrawBackground();
                        e.Graphics.DrawString(item.Row.Field("DisplayMember"), font, brush, e.Bounds);
                        e.DrawFocusRectangle();
                    }
    
                }
    

    Where "DisplayMember" is name of the field to be displayed in the list (set in the ComboBox1.DisplayMember property).

提交回复
热议问题