c# - 用户单击 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);
}
解决方案
让我感到震惊的第一件事是 button_click 方法需要一个object sender
and 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 事件处理程序应该只真正具体地处理事件,并且与按钮所做的任何功能相关的任何功能都应该在单独的方法中。通常一个按钮的工作量很小以至于没有必要,但是像这样的情况说明了为什么它通常是一个好主意。
推荐阅读
- javascript - 带有 Nodemailer 的 HTML2PDF
- java - UTF-8 字符 html 内容字符串到 pdf
- google-apps-script - 我可以使用谷歌应用脚本来开发谷歌浏览器扩展吗
- asp.net-mvc - 任何 .net 应用程序的 IIS 应用程序池崩溃 - PipelineModuleStepContainer 中的 NullReferenceException
- c++-cli - 如何在datagridview中合并单元格,然后将组合框添加到单元格被合并?
- mysql - 如何使用 SQL 在 MS 查询表中仅显示一个最大值(不是一组最大值)?
- java - 理解构造函数的问题,如 ArrayList.class 中的构造函数
- c# - 显示带有部分视图的多个表。ASP.NET MVC
- python - 用于在 python 中训练 ML 模型的导入配置文件
- vue.js - 在 80 端口的 VPS 中运行 vue