首页 > 解决方案 > 用户单击 ASP.NET Web 表单上的按钮与计时器运行调用相同按钮单击事件的方法之间的区别?

问题描述

我创建了一个带有按钮的 ASP.NET Web 表单(页面?),单击该按钮将打开一个 Access 数据库,该数据库运行一个自动执行程序,其目的是运行删除/附加序列,因此我在表中有我需要的数据. 单击事件按钮中的代码也应该刷新网页以显示更新的数据。当用户物理单击按钮时,这在大多数情况下都有效。但是,当我创建一个计时器对象来运行一个调用单击事件的方法时,我收到一个错误:System.NullReferenceException:'对象引用未设置为对象的实例。System.Web.HttpContext.Current.get 返回 null。是什么赋予了?

就像我说的那样,当有物理用户单击按钮时它可以工作,但最终我想自动化打开 Access db 的任务,以及用新数据刷新 Web 表单(页面?)。

这是按钮点击代码。注释行是我已经尝试过的:

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        Process.Start(@"C:\Users\mperea\Desktop\DC8SortMonitor.accdb");           

        HttpContext.Current.Response.Redirect("~/Default.aspx");

        //Response.Redirect("~/Default.aspx");
        //Page.Response.Redirect(Page.Request.Url.ToString(), true);
        //Server.TransferRequest(Request.Url.AbsolutePath, false);

        //Trying open access with this didn't work:
        //Access.Application oAccess = new Access.ApplicationClass();//oAccess.OpenCurrentDatabase(@"C:\Users\mperea\Desktop\DC8SortMonitor.accdb");
    } 

这是计时器对象,旨在以编程方式执行调用点击事件的方法:

    protected void Page_Load(object sender, EventArgs e)
    {

        Timer aTimer;

        //Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 15000;

        //ElapsedEventHandler btnRefresh_Click = null;
        //Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += timer;

        //Have the timer fire repeated events(true is the default)
        aTimer.AutoReset = true;

        //Start the timer
        aTimer.Enabled = true;
     }

以及计时器调用的方法:

    public void timer(object sender, EventArgs e)
    {
        btnRefresh_Click(null, null);
    }

标签: c#asp.netms-accessvisual-studio-2019

解决方案


让我感到震惊的第一件事是 button_click 方法需要一个object senderand EventArgs e,您将其作为 null 传入,因为显然您没有提供它的信息。

您不应该以这种方式调用您的按钮事件处理程序。相反,您应该将共享代码从您的 click 方法移到另一个方法中,该方法不需要您可以从任何地方调用的那些参数。

protected void btnRefresh_Click(object sender, EventArgs e)
{
    Refresh();
} 

现在你的刷新方法

public void Refresh()
{
    Process.Start(@"C:\Users\mperea\Desktop\DC8SortMonitor.accdb");

    Response.Redirect("~/Default.aspx");

    //HttpContext.Current.Response.Redirect("~/Default.aspx");
    //Page.Response.Redirect(Page.Request.Url.ToString(), true);
    //Server.TransferRequest(Request.Url.AbsolutePath, false);

    //Access.Application oAccess = new Access.ApplicationClass();//oAccess.OpenCurrentDatabase(@"C:\Users\mperea\Desktop\DC8SortMonitor.accdb");
}

和定时器

 public void timer(object sender, EventArgs e)
{
    Refresh();
}

click 事件处理程序应该只真正具体地处理事件,并且与按钮所做的任何功能相关的任何功能都应该在单独的方法中。通常一个按钮的工作量很小以至于没有必要,但是像这样的情况说明了为什么它通常是一个好主意。


推荐阅读