c# - 我的加法逻辑在 C# 代码中不起作用

标签 c# asp.net .net

 public partial class Addition : System.Web.UI.UserControl
    {
        int Add1;
        int Add2;
        int answer;

        protected void Page_Load(object sender, EventArgs e)
        {

    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        //Generates ramdom numbers for addition problem
        Random oRand = new Random();

        Add1 = oRand.Next(30);
        Add2 = oRand.Next(30);

        Label1.Text = Add1.ToString();
        Label2.Text = Add2.ToString();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        //Validates users answer
        answer = Convert.ToInt32(TextBox1.Text);

        if (Add1 + Add2 != answer)
            Label3.Text = "InCorrect Answer";
        else
            Label3.Text = "Correct Answer";

        }
    }

在过去的 30 分钟里,我一直在研究这个问题,我知道我缺少的是一些简单的东西。当我执行程序并将正确答案放入 TextBox1 时,Label3 仍然生成“InCorrect Answer”。我知道这是补救措施,但我做错了什么?

谢谢

最佳答案

用户控件在回发时(以及每次加载页面时)重新创建,因此当您设置 Add1Add2 的值时,它们会在回发时丢失.

您应该使用容器 ViewStateSession 来保存这些值。

编辑:

或者如@IronMan84 所建议的那样,只需使用标签 (duh)。

关于c# - 我的加法逻辑在 C# 代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075226/

相关文章:

c# - .NET 和数据库层

c# - 从测试运行 WPF 对话框

asp.net - @RenderBody() 该怎么办?

c# - 在方法之间共享 DTO 类是否会创建有关 'extra' 属性的漏洞?

c# - 如何替换 Linq Cast 表达式?

c# - Entity Framework 代码优先 Fluent API

c# - NUnit 错误 : "FrameworkName cannot have less than two components or more than three components"

c# - 使用 JavaScriptSerializer C# 反序列化 JSON

c# - StructureMap 无法识别 TheCallingAssembly

c# - c#中set和set all的区别