Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created comboBox dynamically. But i need to select the value from " SelectedIndexChanged". But iam getting error as "Object reference not set to an instance of an object."

C#
 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);
            }
        }


What I have tried:

Kindly provide me solution for this.

private void TimeIntervel_SelectedIndexChanged(object sender, EventArgs e)
{
try
{


if (TimeIntervel.SelectedItem != null)
{
Stimer = int.Parse(TimeIntervel.SelectedItem.ToString());
}
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}
}
Posted
Updated 22-Aug-16 0:48am

1 solution

You try to handle the
C#
private ComboBox TimeIntervel;

but instead you have created another one, and the TimeIntervel is not populated. Rename the TimeIntervel to TimeIntervelCMB


C#
private ComboBox TimeIntervelCMB;
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.AddRange({500,1000,2000,3000,4000,5000,6000});
 
Share this answer
 
v2
Comments
vinodh muthusamy 22-Aug-16 7:09am    
thank you.
it is working fine.
[no name] 22-Aug-16 7:25am    
mark this thread as solved by accepting this solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900