记住点击按钮

时间:2014-04-23 23:11:13

标签: c# asp.net

我在网页上隐藏了以下代码,并尝试将输出显示在列表框中

1 + 1 = 2

我遇到的问题是记住按下的操作按钮并将其添加到列表框中。当前输出是

1 ButtonSave 1 = 2

ButtonSave是点击的最后一个按钮

namespace calcpage
{
   public partial class Default : System.Web.UI.Page
   {
      protected void ButtonAdd_Click(object sender, EventArgs e)
      {
         if (!string.IsNullOrEmpty(TextBox1.Text) && 
            !string.IsNullOrEmpty(TextBox2.Text))
            TextBox3.Text = (Convert.ToInt32(TextBox1.Text) +
            Convert.ToInt32(TextBox2.Text)).ToString();
        Label3.Text = string.Empty;
        ViewState["LastButtonClicked"] = ButtonAdd.ID;
      }

      protected void ButtonSub_Click(object sender, EventArgs e)
      {
         if (!string.IsNullOrEmpty(TextBox1.Text) &&
            !string.IsNullOrEmpty(TextBox2.Text))
            TextBox3.Text = (Convert.ToInt32(TextBox1.Text) -
            Convert.ToInt32(TextBox2.Text)).ToString();
         Label3.Text = string.Empty;
         ViewState["LastButtonClicked"] = ButtonSub.ID;
      }

      protected void ButtonMul_Click(object sender, EventArgs e)
      {
         if (!string.IsNullOrEmpty(TextBox1.Text) && 
            !string.IsNullOrEmpty(TextBox2.Text))
            TextBox3.Text = (Convert.ToInt32(TextBox1.Text) *
            Convert.ToInt32(TextBox2.Text)).ToString();
         Label3.Text = string.Empty;
         ViewState["LastButtonClicked"] = ButtonMul.ID;
      }

      protected void ButtonDiv_Click(object sender, EventArgs e)
      {
         try
         {
            if (!string.IsNullOrEmpty(TextBox1.Text) && 
               !string.IsNullOrEmpty(TextBox2.Text))
               TextBox3.Text = (Convert.ToInt32(TextBox1.Text) / 
               Convert.ToInt32(TextBox2.Text)).ToString();
               ViewState["LastButtonClicked"] = ButtonDiv.ID;
         }
         catch
         {
            if (TextBox2.Text == "0")
            {
               TextBox3.Text = string.Empty;
               Label3.Text = "You can't divide by 0, try another number";
            }
         }
      }         

      protected void ButtonReset_Click(object sender, EventArgs e)
      {
         TextBox1.Text = string.Empty;
         TextBox2.Text = string.Empty;
         TextBox3.Text = string.Empty;
         Label3.Text = string.Empty;
      }

      protected void ButtonSave_Click(object sender, EventArgs e)
      {
         var lastButtonClicked = (string)ViewState["LastButtonClicked"];

         if (ListBox1.Items.Count < 10)
         {
            ListBox1.Items.Add(TextBox1.Text + (" ") + lastButtonClicked + 
            (" ") + TextBox2.Text + (" ") + ("=") + (" ") + TextBox3.Text);
         }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

尝试使用视图状态。它用于在请求之间保持任何状态。

在此处设置

ViewState["LastButtonClicked"] = someButton.Id;

在此处获取

var lastButtonClicked = (string)ViewState["LastButtonClicked"];