Reputation: 65
I have created a ComboBox
dynamically, but I need to select the value from SelectedIndexChanged
. I am getting the following error:
Object reference not set to an instance of an object
private ComboBox TimeIntervel;
int Stimer;
public void set control()
{
ComboBox TimeIntervelCmb = new ComboBox();
TimeIntervelCmb.Location = new Point(50,70);
TimeIntervelCmb.Name = "ComboBoxTime";
TimeIntervelCmb.Size = new Size(80, 100);
TimeIntervelCmb.Items.Add("500");
TimeIntervelCmb.Items.Add("1000");
TimeIntervelCmb.Items.Add("2000");
TimeIntervelCmb.Items.Add("3000");
TimeIntervelCmb.Items.Add("4000");
TimeIntervelCmb.Items.Add("5000");
TimeIntervelCmb.Items.Add("6000");
TimeIntervelCmb.SelectedIndexChanged += new EventHandler(TimeIntervel_SelectedIndexChanged);
this.Controls.Add(TimeIntervelCmb);
}
private void TimeIntervel_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (TimeIntervel.SelectedItem != null)// Object reference not set to an instance of an object.-Error
{
Stimer = int.Parse(TimeIntervel.SelectedItem.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Upvotes: 0
Views: 537
Reputation: 13394
You create a ComboBox
in a local variable named TimeIntervelCmb
and never assign it to TimeIntervel
, therefore TimeIntervel
will always be null.
Add this line:
TimeIntervel = TimeIntervelCmb;
Or check the ComboBox
instance that raises the event:
ComboBox combo = (ComboBox)sender;
if (combo .SelectedItem != null)
// etc ...
Upvotes: 1