【问题标题】:Increment the int value in the text box增加文本框中的 int 值
【发布时间】:2012-11-26 00:30:32
【问题描述】:

我有一个禁用的文本框,它的值只会在单击按钮后增加一,问题是它从 1 变为 2,仅此而已。我希望每次按下按钮时它都会增加。

namespace StudentSurveySystem
{
    public partial class AddQuestions : System.Web.UI.Page
    {
        int num = 1;

        protected void Page_Load(object sender, EventArgs e)
        {

            QnoTextBox.Text = num.ToString();

        }

        protected void ASPxButton1_Click(object sender, EventArgs e)
        {
            num += 1;
            QnoTextBox.Text = num.ToString();
        }
    }
}

【问题讨论】:

    标签: c# asp.net increment


    【解决方案1】:

    Postback intializes the variable num to 1 again 并且您没有得到预期的增量结果,您最好使用文本框值并将该值存储在 ViewState 中。

    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        num = int.Parse(QnoTextBox.Text);
        num++;
        QnoTextBox.Text = num.ToString();
    }
    

    使用 ViewState

    public partial class AddQuestions : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
            if(!Page.IsPostBack)
                ViewState["Num"] = "1";
    
        }
    
        protected void ASPxButton1_Click(object sender, EventArgs e)
        {           
            QnoTextBox.Text = ViewState["Num"].ToString();
            int num = int.Parse(ViewState["Num"].ToString());
            ViewState["Num"] = num++;
        }
    }
    

    【讨论】:

    • 我刚刚在页面加载中添加了 if(!ispostback) 并且它起作用了。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2019-02-08
    • 2011-05-16
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多