Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve an "InvalidCastException"?

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?

like image 850
gallie Avatar asked Oct 17 '25 10:10

gallie


1 Answers

You have to check if it is an integer.

int competitionFormat;
bool result = Int32.TryParse(cbCompetitionFormat.SelectedValue, out competitionFormat);

if (result) { }
like image 85
COLD TOLD Avatar answered Oct 18 '25 23:10

COLD TOLD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!