在计时器刻度事件中显示新表格

时间:2013-07-05 17:19:55

标签: c# sql database winforms timer

我已连接到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 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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();
    }

答案 2 :(得分: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();
     }
   }

答案 3 :(得分:0)

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

相关问题