我在主窗体中有一个计时器,但我想通过第二个子窗体更改计时器的间隔。但是,在获取文本框文本时,子窗体中有一个"System.NullReferenceException",代码如下所示。任何建议,示例,提示或帮助将不胜感激。
带有计时器的主窗体(通过设计器添加(;
public partial class Booyaa : Form
{
private void Booyaa_Load(object sender, EventArgs e)
{
BooyaaTimer.Interval = 45 * 60 * 1000); // 45 mins
BooyaaTimer.Tick += new EventHandler(BooyaaTimer_Tick);
BooyaaTimer.Start();
if (!Properties.Settings.Default.SettingShutdown)
{
MessageBox.Show("Time");
GetPass pass = new GetPass();
DialogResult result = pass.ShowDialog();
if (result == DialogResult.OK)
{
Properties.Settings.Default.SettingShutdown = true;
Properties.Settings.Default.Save();
}
else
{
Close();
}
}
}
}
定时器控制的其他子窗体:
public partial class TimerControl : Form
{
public static Timer BooyaaTimer { get; internal set; }
public TimerControl()
{
InitializeComponent();
}
private void btn_confirm_Click(object sender, EventArgs e)
{
BooyaaTimer.Interval = Int32.Parse(textBox1.Text);
}
}
正如@gusman所指出的,检查主窗体Booyaa
窗体以确保BooyaaTimer
存在(即它不为空(。如果您没有将计时器控件拖放到表单上,请确保在表单的构造函数中调用BooyaaTimer = new Timer()
。
因此,如果到目前为止一切正常,则不会将计时器传递给子窗体。如果GetPass
实际上是TimerControl
(我怀疑(,那么您需要像这样修改Booyaa_Load
调用:
MessageBox.Show("Time");
GetPass pass = new GetPass();
/*****-----------******/
pass.BooyaaTimer = BooyaaTimer;//set sub-form's property
DialogResult result = pass.ShowDialog();
此外,在子窗体中,在使用将从其他地方设置的对象之前检查空值并没有什么坏处。
if(BooyaaTimer!=null)
BooyaaTimer.Interval = Int32.Parse(textBox1.Text);
接下来,尝试使用 int。尝试解析。