Reputation: 143
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?
Upvotes: 4
Views: 45983
Reputation: 4291
The problem lies here:
private void cbCompetitionFormat_SelectedIndexChanged(object sender, EventArgs e)
{
int competitionFormat = 1;
competitionFormat = (int)cbCompetitionFormat.SelectedValue; // <- This is an invalid cast
}
SelectedValue
returns just that - the selected value, NOT the selected index. Using the property SelectedIndex
will return what you want (0 indexed), and (I think) you don't even need to cast it:
competitionFormat = cbCompetitionFormat.SelectedValue;
Upvotes: 1
Reputation: 13569
You have to check if it is an integer.
int competitionFormat;
bool result = Int32.TryParse(cbCompetitionFormat.SelectedValue, out competitionFormat);
if (result) { }
Upvotes: 2
Reputation: 143
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.
Upvotes: 1
Reputation: 26376
Try this
competitionFormat = Convert.ToInt32(cbCompetitionFormat.SelectedValue);
Update:
The behaviour of SelectedValue in winforms is that it returns an System.Data.DataRowView
object representing the underlying bound data. This, obviously cannot be converted to integer. You can cast this object to the type of object that was originally bound to the combobox
competitionFormat = ((Competition) cbCompetitionFormat.SelectedValue).CompetitionFormatId;
Upvotes: 0
Reputation: 714
Like the exception implies, you're trying to cast a string to an int, which is invalid. Instead, you should call something like:
competitionFormat = int.Parse(cbCompetitionFormat.SelectedValue);
Upvotes: 1