Pretty specific and weird problem here, Google and the rest couldn't give me an answer.
I have a form with two ComboBoxes, we'll say A and B. Selecting an item in A pulls some info from a database, puts it in Dictionary, and uses BindingSource to put it in B. When the user selects something from B, return values are set and nothing else.
The problem is with ComboBox B. In its SelectedIndexChanged handler, attempting to unbox its SelectedItem causes the ComboBox to 'freeze' so it no longer displays the result of new selections from ListBox B and long lists do not refresh when scrolled up/down. The ComboBox still functions, though, if you remember where the data is
The SelectedIndexChanged Handler of B:
private void comboBox2_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (dataSourceSelect)
return;
else
{
ComboBox comboBox = (ComboBox)sender;
var dummy = comboBox2.SelectedItem;
// System.Collections.Generic.KeyValuePair<int, string> dummy2 =
// (System.Collections.Generic.KeyValuePair<int, string>)dummy;
}
}
There are two dummy variables to show that it isn't the SelectedItem property causing the problem, only the unboxing.
Using this exact code lets ComboBox work correctly, but it's unable to return data. Enabling the commented-out line lets it return values, but stops it from refreshing.
There are two things this code won't show:
Even if you put the commented line in, everything works fine until you do a second selection from ComboBox A. Put another way, if you select from ComboBox A once, ComboBox B will refresh based on your input. But if the selection from A is changed, B freezes the last value shown, and long lists no longer update when scrolled.
The code that fills ComboBox A and B are nearly identical, as are their click handlers, yet A works without any problem all the time, and B freezes when you do a second selection from A.
I can only theorize as to the cause of this, but my guess is that unboxing uses some temp memory location that hates to be touched twice. There might also be some problem with the code that populates B based on A's selection, but the fact that it works fine when unboxing is commented out reduces that suspicion.
From what I can tell, I need to do one of the following:
- Access SelectedItem in another fashion
- Access the data in SelectedItem without unboxing
- Find a method that avoids unboxing altogether
Apologies for the formatting, StackOverflow seems to be ignoring my attempts to make it more readable
SelectedItem.GetType()
? Are you sure that the cast is not throwing an exception? – Thomas LevesqueKeyValuePair``2
just means that KeyValuePair is a generic type with 2 type parameters; usually the type arguments are specified between square brackets. Anyway, yes, it's possible that the SelectedItem is null at some point, so you need to check whether it's null before you cast. Trying to unbox a null value will always fail. – Thomas Levesque