Reputation: 17
For my project I'm using a library and it has a list of pre-defined options. I want to be able to choose from a comboBox so I don't need to edit the source everytime.
main code: Searches for a player. Level can either be set as Gold, Silver, Bronze or All. I want to be able to choose that from comboBox. The error at the end shows when I click a button to run this code.
var searchRequest = new SearchRequest();
var searchParameters = new PlayerSearchParameters
{
Page = 1,
Level = comboBox1.SelectedItem == null ? Level.All : (Level)(comboBox1.SelectedItem as ComboboxItem).Value,
//usually set like this Level - Level.Gold,
};
comboBox code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (Level level in Enum.GetValues(typeof(Level)))
{
ComboboxItem item = new ComboboxItem();
item.Text = level.ToString();
item.Value = level;
comboBox1.Items.Add(item);
}
}
ComboboxItem code:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
I thought that all of this would work but it give an error saying NullReferenchExeption was unhanded by user code. and Object reference not set to an instance of an object.
I really need help with getting this to work.
All help is really appreciated.
Thanks,
Jack.
Upvotes: 1
Views: 1345
Reputation: 63065
you can bind the comboBox1
directly from enum as below
comboBox1.DataSource =Enum.GetNames(typeof(Level));
then if you need to get selected enum
Level level ;
if( Enum.TryParse<Level>(comboBox1.SelectedValue.ToString(), out level))
{
var searchParameters = new PlayerSearchParameters
{
Page = 1,
Level =level
};
}
Upvotes: 1
Reputation: 10026
After running what you have posted here - the only time that I receive a NullReferenchExeption
is when I click the search button when nothing has been selected in the Combobox
yet.
You need to check for null first. Like so...
if (comboBox1.SelectedItem != null)
{
var searchRequest = new SearchRequest();
var searchParameters = new PlayerSearchParameters
{
Page = 1,
Level = (Level)(comboBox1.SelectedItem as ComboboxItem).Value,
//usually set like this Level - Level.Gold,
};
}
Upvotes: 0