在动态控制组合框中获取选定项
本文关键字:获取 动态控制 组合 | 更新日期: 2023-09-27 18:03:27
我已经动态地创建了一个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);
}
}
您在名为TimeIntervelCmb
的局部变量中创建了ComboBox
,并且从未将其分配给TimeIntervel
,因此TimeIntervel
将始终为空。
添加这一行:
TimeIntervel = TimeIntervelCmb;
或者检查引发事件的ComboBox
实例:
ComboBox combo = (ComboBox)sender;
if (combo .SelectedItem != null)
// etc ...