ComboBox exception caused in winforms FormClosing event
Using c# vs2008 winforms
I have an application with a bunch of child winforms. Each time a form is closed I need to store the current selected value of a combobox that is on each form to a Global application variable so that I can track it and use it in new forms. The combobox is populated on form start via a method to set its datasource to an ArrayList of items
What I have found is if the combobox is populated with items in the designer, and you try to get the combobox value in the form closing event, I always get a NullReferenceException.
However if the comboBox has an datasource like I DO have in my application and I try to get the combobox value in the form closing event then I would say 95% of the time I DO NOT get the NullReferenceException, but I do get it 5% of the time. That ratio can even vary depending on what computer I run the application on. for example I have 1 computer where the exception always occurs.
My question is therefore what is (the best) way to get the value of the combobox, last thing before the form closes without causing the开发者_如何学编程 exception. I would def prefer to do it last thing before the form closes rather than track it with every selected index change event.
Any advice appreciated.
I'm guessing you're current implementation then is actually using the event handler. I'm not sure where you're trying to grab the value in your code, whether it's the form code itself or somewhere else.
What I'd probably do is the following:
protected override void OnClosing(CancelEventArgs e)
{
// Save Value
base.OnClosing(e);
}
Are you using the SelectedValue
property of the combobox to access the selected item? This returns...
An object containing the value of the member of the data source specified by the ValueMember property. (MSDN)
If you haven't specified a ValueMember
, this could be the problem. If you want to simply access the string value as displayed in the combobox, try using the SelectedText
property instead.
精彩评论