'How to set the SelectedValue of a ComboBox used as Font selector?

I have a combobox which I fill font's inside. The method I use to do so is in this link. I will share the answer from that question here.

public YourForm()
{
    InitializeComponent();

    ComboBoxFonts.DrawItem += ComboBoxFonts_DrawItem;           
    ComboBoxFonts.DataSource = System.Drawing.FontFamily.Families.ToList();
}

private void ComboBoxFonts_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);
}

now I have only made 1 change to this code and that's this :

cmbFonts.DrawMode = DrawMode.OwnerDrawFixed;

there is no problem with loading fonts and it's working but I try to set the selectedvalue on my form load. For example I try to set font named "arial". In order to do so I use this :

var dataSource = cmbFonts.DataSource as List<FontFamily>;
int res = -1;
try
{
  res = dataSource.IndexOf(new FontFamily(StaticVariables.FontName));
}
catch { }
if (res != -1)
  cmbFonts.SelectedIndex = res;

now when I do this I get System.ArgumentOutOfRangeException error because I did not add any Items to Combobox I bind a DataSource therefore when I try to set SelectedIndex I get this error and I know that, I also tried this :

cmbFonts.SelectedValue = StaticVariables.FontName;

but when I run my code with breakpoints in Visual studio I see that my SelectedValue never changes. Before the line is executed I see null and after the execution I still see null in SelectedValue, I checked my StaticVariables.FontName variable and the font is presented in there.

I've also tried to use combobox.Text property but no luck, it's like SelectedValue, was empty string before and still same after I skip it with breakpoint.

TL;DR: I try to select an item on form load in combobox which I filled with DataSource



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source