0

我已连接到 SQL Server 数据库并且可以执行简单的 CRUD 操作。现在我想让我的应用程序在我的数据库中的一个人今天过生日时显示第二个Form (提醒表单),但是当我运行我的应用程序时没有任何反应。

编辑:我的提醒表单现在正确显示,但是当我尝试关闭该表单时,我收到此错误消息:

无法访问已处置的对象。对象名称:'Form2'。

这是我的代码:

public partial class Form1 : Form
{
    Timer timer = new Timer();
    Form2 forma = new Form2();

    public Form1()
    {
        InitializeComponent();
        var data = new BirthdayEntities();
        dataGridView1.DataSource = data.Tab_Bday.ToList();

        timer.Tick += new EventHandler(timer_Tick); 
        timer.Interval = (1000) * (1);             
        timer.Enabled = true;                       
        timer.Start();                              
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        Boolean flag = false;
        IQueryable<Tab_Bday> name;

        using (var data2 = new BirthdayEntities())
        {
            name = (from x in data2.Tab_Bday
                    select x);

            foreach (var x in name)
            {
                if (x.Datum.Day == System.DateTime.Now.Day && x.Datum.Month == System.DateTime.Now.Month)
                {
                    flag = true;
                    break;
                }
            }
        }

        if (flag == true)
            forma.Show();
    }
4

4 回答 4

0

这就是你应该如何设置你的Timer.

public void TimerSetup() {
    Timer timer1 = new Timer();
    timer1.Interval = 1000;     //timer will fire every second
    timer1.Tick += OnTimedEvent;
    timer1.Enabled = true;
    timer1.Start();
}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
于 2013-07-05T17:29:37.347 回答
0

这应该有效。记得启动和停止计时器。

    Timer timer = new Timer();
    timer.Interval = 1000; // 1 second
    timer.Tick += new EventHandler(timer_Tick);
    timer.Start();

    private void timer_Tick( object sender, EventArgs e ) {
        Timer timer = (Timer)sender;
        timer.Stop();
        new Form().ShowDialog();
    }
于 2013-07-05T17:39:32.877 回答
0

如果你想在关闭它时显示你的提醒表单而不抛出这样的异常,有两种方法:

1. Create new Reminder form every time you want to show it.
2. Add code to `FormClosing` event handler to Cancel the Closing operation and just hide it instead like this:

    public Form1()
   {
     InitializeComponent();
     var data = new BirthdayEntities();
     dataGridView1.DataSource = data.Tab_Bday.ToList();
     //add this
     forma.FormClosing += forma_FormClosing;
     timer.Tick += new EventHandler(timer_Tick); 
     timer.Interval = (1000) * (1);                      
     timer.Start();                              
   }
   private void forma_FormClosing(object sender, FormClosingEventArgs e){
     if(e.CloseReason == CloseReason.UserClosing){
         e.Cancel = true;
         forma.Hide();
     }
   }
于 2013-07-06T01:37:55.823 回答
0

问题是您正在通过计时器滴答声访问表单,这意味着在您关闭计时器滴答声中的“处置”表单后,您正在尝试再次访问它,因此您需要三思而后行(我遇到了同样的问题,所以我刚刚在处理的表单上停止了计时器)希望快速帮助其他人,因为这个线程很旧。

于 2021-02-18T21:29:15.647 回答