记住按钮点击了
本文关键字:按钮 | 更新日期: 2023-09-27 17:59:59
我在一个网页上有下面的代码,并试图将输出显示在列表框中作为
1+1=2
我遇到的问题是记住按下的操作按钮并将其添加到列表框中。当前输出为
1按钮保存1=2
按钮保存是最后一个点击的按钮
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);
}
}
}
}
尝试使用视图状态。它用于在请求之间保持任何状态。
在此处设置
ViewState["LastButtonClicked"] = someButton.Id;
在这里获取
var lastButtonClicked = (string)ViewState["LastButtonClicked"];