文件背后的C#代码无法识别变量的变化 [英] C# code behind file not recognising change in variable

查看:103
本文介绍了文件背后的C#代码无法识别变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码隐藏文件,在页面加载时设置一个表单。此表单有一个下拉列表,用于选择您要查看的表单。



当选择不同的视图时,会调用onSelectedIndexChanged方法,我可以看到这个被调用。当索引更改时,它会根据所选内容设置一个全局布尔值,例如,如果选择

formula,则bool form = true;



因此,当我填写表单并单击提交时,onClick事件被触发,但它仍然认为bool是假的,它没有识别变量值的变化,



有没有人可以为我清除这个...下面的基本代码



I have a code behind file that on page load sets up a form. this form has a dropdownlist to select which form you'd like to view.

When selecting a different view a onSelectedIndexChanged method is called, i can see this is being called. When the index changes it sets a global boolean depending on what is selected, e.g if
"formulation" is selected global bool form = true;

therefore later when i have filled in the form and click submit the onClick event is fired, but it still thinks the bool is false, it is not recognising the change in variable value,

is there anyone out there that can clear this up for me.. basic code below

public partial class ProductSearch : PageBase
{
    StringBuilder builder;
    List<string> errorMessages;
    Document doc;
    bool formulationSearch = false;
    bool batchSearch = false;

    protected void Page_Load(object sender, EventArgs e)
    {


        if (!Page.IsPostBack)
        {
            errorMessages = new List<string>();
            SetupBatchForm();
            SetupLanguageSelect();
            language_select.SelectedValue = "2";
        }
    }
private void SetupBatchForm()
    {
        search_by.SelectedValue = "batch";
        batchSearch = true;
        batch_input.Visible = true;
        batch_help.Visible = true;
        formulation_input.Visible = false;
        formulation_help.Visible = false;

     }



代码提交按钮onClick




code Submit button onClick

protected void SubmitSearch(object sender, EventArgs e)
    {
        Response.Write("Submited");
        Response.Write(batchSearch);
        if (batchSearch)
        {
            SubmitBatchSearch();
        }
        else
        {
            SubmitFormulationSearch();
        }
            
        
    }

推荐答案

这是因为webforms不能像窗户形式。设置变量时,它仅对该连接有效。当您的页面回发所有C#运行时,然后将一堆html发送到客户端并断开连接。因此,您在课堂上设置的任何变量都将丢失。下次页面回发时,例如单击按钮,会创建一个新的类实例。



要保留信息,您可能希望改为写入值进入隐藏字段或使用会话或其他形式的持久存储。
This is because webforms do not work like windows forms. When you set a variable it is only valid for that connection. When your page posts back all of your C# runs and then a bunch of html is sent to the client and you are disconnected. So, any variables you had set in your class are lost. The next time the page postsback, such as a button click, there is a new instance of your class created.

To persist information you may want to instead write the value into a hidden field or use the session or some other form of persistent storage.


这篇关于文件背后的C#代码无法识别变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆