rjh357
rjh357

Reputation: 11

how to set multiple Font Styles when checked Combobox in c#

I'd like to font style and font size in Combobox. When I selected font size after selected font style then, I select font style in Combobox again it did not work.

How can I solve it?

private void FontBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(FontBox.Text, RichTextBox.Font.Size);
    }
    catch { }
}

private void font_sizeBox_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        RichTextBox.SelectionFont = new Font(RichTextBox.Font.FontFamily, 
            float.Parse(font_sizeBox.SelectedItem.ToString()));
    }
    catch { }
}

Upvotes: 1

Views: 187

Answers (2)

Bob
Bob

Reputation: 575

To display the fonts in a ComboBox with it's respective styles, we have to set the ComboBox DrawMode property from, Normal to DrawItemFixed. Then we can use the DrawItem event:

    public Form1()
    {
        InitializeComponent();
        comboBox1.DrawItem += comboBox1_DrawItem;
        comboBox1.DataSource = System.Drawing.FontFamily.Families.ToList();
    }

Here, we're creating the Method comboBox1_DrawItem and assigning the DataSource for the ComboBox as the current installed Font-families.

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        var comboBox = (ComboBox)sender;
        var fontFamily = (FontFamily)comboBox.Items[e.Index];
        var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

        e.DrawBackground();
        e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
    }

Then this should be the DrawItem method. You can also set comboBox1.DrawMode = DrawMode.OwnerDrawFixed; in the public of your form.

Upvotes: 2

Always_a_learner
Always_a_learner

Reputation: 1304

Try setting like this:

richTextBox1.SelectAll();
richTextBox1.SelectionFont = newFont;

Upvotes: 0

Related Questions