简体   繁体   English

从C#背后的代码中的另一个方法调用一个方法

[英]call a method from another method in Code behind C#

I need to call btn_submit_Click(object sender, EventArgs e) from another method protected void Timer1_Tick(object sender, EventArgs e) which normally calls by a button click. 我需要调用btn_submit_Click(object sender, EventArgs e)从另一种方法protected void Timer1_Tick(object sender, EventArgs e)通常通过点击一个按钮调用。

Now here in Timer1_Tick compares a time and if current time exceeds, i need to call btn_submit_Click(object sender, EventArgs e) automatically. 现在在Timer1_Tick比较一个时间,如果当前时间超过,我需要自动调用btn_submit_Click(object sender, EventArgs e)

  protected void Timer1_Tick(object sender, EventArgs e)
    {
        DateTime et = DateTime.Parse(Session["endtime"].ToString());

        if (DateTime.Now.TimeOfDay >= et.TimeOfDay)
        {
           // btn_submit_Click();
            Response.Redirect("Welcome.aspx");

        }
        else
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
        }
    }

Please suggest me a way to do this. 请给我建议一种方法。

Personally I would take a slightly different approach. 我个人会采取略有不同的方法。 You're not actually trying to say that a button was clicked - you're just interested in the same side effects as a button click. 您实际上并不是要说单击了按钮-您只是对与单击按钮相同的副作用感兴趣。 So extract a third method which only has the relevant parameters (there may not be any) and call that method from both btn_submit_Click and Timer1_Tick . 因此,提取仅具有相关参数(可能没有任何参数)的第三个方法,然后从btn_submit_ClickTimer1_Tick调用该方法。 That way you don't have to come up with a sender and EventArgs for a button click which didn't happen. 这样,您不必为没有发生的按钮点击提供senderEventArgs So for example: 因此,例如:

protected void btn_submit_Click(object sender, EventArgs e)
{
    // Maybe validation?
    Submit();
}

protected void Timer1_Tick(object sender, EventArgs e)
{
    DateTime et = DateTime.Parse(Session["endtime"].ToString());

    if (DateTime.Now.TimeOfDay >= et.TimeOfDay)
    {
        Submit();
        Response.Redirect("Welcome.aspx");
    }
    else
    {
        Label1.Text = DateTime.Now.ToLongTimeString();
    }
}

private void Submit()
{
    // Common code to execute on either the timer tick or button click
}

Jon Skeet mentioned the right approach. 乔恩·斯基特(Jon Skeet)提到了正确的方法。 Refactor the code in your btn_submit_click into a central method that can be called by both Button and Timer. btn_submit_click的代码重构为可以由Button和Timer调用的中央方法。 But you can still do submit_click(sender, e) 但是您仍然可以执行submit_click(sender, e)

protected void Timer1_Tick(object sender, EventArgs e)
{
      ....
      btn_submit_Click(sender, e);
      ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM