当在c#中点击Button时,变量会被重新初始化

本文关键字:变量 初始化 Button 当在 | 更新日期: 2023-09-27 18:15:55

我正在制作一个在线表单。我初始化4个变量在我的代码开始。当我选择一个下拉菜单时,触发一个事件(DropDownList4_SelectedIndexChanged),然后调用Availability()。这里我的布尔变量avail_bus被赋值。然而,当我点击提交按钮(Button1_Click1)时,变量avail_bus被重新初始化为false。我对此进行了调试,发现在单击Submit(Button1_Click1)时,控件首先转到页面中

代码的顶部。
public partial class Appform : System.Web.UI.Page
    {
        private bool isNotDup = true;
        private bool avail_bus ;
        private int max_capacity_bus;
        private int realAvailability;
}
然后转到Button1_click1。我怎样才能避免这种情况的发生?如果在调用availability时将avail_bus的状态更改为true,则在单击submit时不应将其重新初始化为true。下面是我的代码:
namespace eTransport
{
    public partial class Appform : System.Web.UI.Page
    {
        private bool isNotDup = true;
        private bool avail_bus ;
        private int max_capacity_bus;
        private int realAvailability;
        protected void Page_Load (object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BindDropDown();

            }
        }
        //Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
        protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
        {
            AutoPopulateBusStop();
            Availability();
        }

        //Method to load drop down values in Bus Stop. These are populated from database
        protected void BindDropDown ()
        {
           //some code here
        }
        //Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
        protected void AutoPopulateBusStop ()
        {
            //some code here
        }

        protected void Availability ()
        {
            string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            using (SqlConnection con5 = new SqlConnection(constr5))
            {
                try
                {
                    using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
                    {
                        cmd5.CommandType = CommandType.Text;
                        cmd5.Connection = con5;
                        con5.Open();
                        int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
                        realAvailability = max_capacity_bus - capacity_from_db;
                        if (realAvailability > 0)
                        {
                            avail_bus = true;
                            TextBox2.Text = realAvailability.ToString() + " seats available ";
                            TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
                        }
                        else
                        {
                            TextBox2.Text = "Seats Not available. Please choose another Stop";
                            TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
        }

        protected void Button1_Click1 (object sender, EventArgs e)
        {

            if (isNotDup)
            {
                if (avail_bus)
                {
                   // Submit the Form
                }
                else
                {
                    Label14.Text = "Bus Seats not available!";
                    Label15.Text = null;
                }
            }
        }

        protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
        {
           //some code here

        }

         }
}

当在c#中点击Button时,变量会被重新初始化

这个问题有三种可能的解决方案。

Static -这将创建一个可访问所有页面的实例(全局)

private static avail_bus = true;

会话状态-这允许您在用户导航时存储和检索用户的值。

// Get...
private bool avail_bus = (bool)Session["avail_bus"];
// Set
Session["avail_bus"] = true;

控制。ViewState—获取状态信息的字典,该字典允许您保存和恢复服务器控件在同一页面的多个请求中的视图状态。

public bool avail_bus
{
    get { return  ViewState["avail_bus"] == null ? false : (bool)ViewState["avail_bus"]; }
    set { ViewState["avail_bus"] = value; }
}

每次有对页面的请求时,都会创建该页面类的一个新实例来处理该请求。所以所有字段都被重新初始化。

您可以在ViewState中存储一个值,以便在各种请求中记住一个值:

namespace eTransport
{
    public partial class Appform : System.Web.UI.Page
    {
private bool isNotDup 
{
   set { ViewState["isNotDup "] = value; }
   get 
   {
      if (ViewState["isNotDup "] == null)
         return true;
      return (bool )ViewState["isNotDup "];
   }
}
private bool avail_bus 
{
   set { ViewState["avail_bus"] = value; }
   get 
   {
      if (ViewState["avail_bus"] == null)
         return true;
      return (bool )ViewState["avail_bus"];
   }
}
private int max_capacity_bus 
{
   set { ViewState["max_capacity_bus "] = value; }
   get 
   {
      if (ViewState["max_capacity_bus "] == null)
         return 0;
      return (int)ViewState["max_capacity_bus "];
   }
}
private int realAvailability
{
   set { ViewState["realAvailability"] = value; }
   get 
   {
      if (ViewState["realAvailability"] == null)
         return 0;
      return (int)ViewState["realAvailability"];
   }
}
    protected void Page_Load (object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BindDropDown();

            }
        }
        //Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
        protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
        {
            AutoPopulateBusStop();
            Availability();
        }

        //Method to load drop down values in Bus Stop. These are populated from database
        protected void BindDropDown ()
        {
           //some code here
        }
        //Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
        protected void AutoPopulateBusStop ()
        {
            //some code here
        }

        protected void Availability ()
        {
            string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            using (SqlConnection con5 = new SqlConnection(constr5))
            {
                try
                {
                    using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
                    {
                        cmd5.CommandType = CommandType.Text;
                        cmd5.Connection = con5;
                        con5.Open();
                        int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
                        realAvailability = max_capacity_bus - capacity_from_db;
                        if (realAvailability > 0)
                        {
                            avail_bus = true;
                            TextBox2.Text = realAvailability.ToString() + " seats available ";
                            TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
                        }
                        else
                        {
                            TextBox2.Text = "Seats Not available. Please choose another Stop";
                            TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
        }

        protected void Button1_Click1 (object sender, EventArgs e)
        {

            if (isNotDup)
            {
                if (avail_bus)
                {
                   // Submit the Form
                }
                else
                {
                    Label14.Text = "Bus Seats not available!";
                    Label15.Text = null;
                }
            }
        }

        protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
        {
           //some code here

        }

         }
}

您可以将可用性状态存储在隐藏的输入字段中,稍后在Button1单击事件时发布。

在button1中,点击事件而不是从变量访问avail值从hiddenField的值访问它

另一个选项是在button1的click event中再次调用Availability()作为第一行,以便它在avail_bus变量

中设置适当的值