我动态创建了ComboBox
,但我需要从SelectedIndexChanged
中选择值。我收到以下错误:
对象引用未设置为对象的实例
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);
}
}
答案 0 :(得分:1)
您在名为ComboBox
的本地变量中创建了TimeIntervelCmb
,但从未将其分配给TimeIntervel
,因此TimeIntervel
将始终为空。
添加以下行:
TimeIntervel = TimeIntervelCmb;
或者查看引发事件的ComboBox
实例:
ComboBox combo = (ComboBox)sender;
if (combo .SelectedItem != null)
// etc ...