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?
You have to check if it is an integer.
int competitionFormat;
bool result = Int32.TryParse(cbCompetitionFormat.SelectedValue, out competitionFormat);
if (result) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With