I’m getting an “InvalidCastException” during run time on the following code:
My C# WinForm code contains a comboBox which is populated from a database with the following code:
public void PopulateCompetitionFormatDd()
{
var _competitionFormat = new CompetitionFormatBL();
cbCompetitionFormat.DataSource = _competitionFormat.GetByAllCompetitionFormats();
cbCompetitionFormat.ValueMember = "CompetitionFormatId";
cbCompetitionFormat.DisplayMember = "CompetitionFormatType";
}
The ValueMember (CompetitionFormatId) is a list of numbers and the DisplayMember (CompetitionFormatType) is a string of text. When I change the item in this comboBox during run time I get the error “InvalidCastException“.
private void cbCompetitionFormat_SelectedIndexChanged(object sender, EventArgs e)
{
int competitionFormat = 1;
competitionFormat = (int)cbCompetitionFormat.SelectedValue;
}
Any ideas what i’m doing wrong and how I can get around it?
I finally got the answer to this and it’s answered on this site to another similar question. Find answer here: Stop comboBox's selectedIndexChanged event from firing when the form loads
The answer is:
If you want to react only when the user changes the selected item in the combo box, then it is better to subscribe to SelectionChangeCommitted rather than SelectedIndex(or Value)Changed.