单击C#中的Button时重新初始化的变量

时间:2015-10-05 05:29:06

标签: c# asp.net boolean

我正在制作在线表格。我在开头的代码中初始化了4个变量。当我选择一个下拉列表时,会触发一个事件(DropDownList4_SelectedIndexChanged),然后调用Availability()。这里我的布尔变量 avail_bus 被赋值。但是,当我单击提交按钮(Button1_Click1)时,变量 avail_bus 将重新初始化为false。我调试了这个,发现在点击提交(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 。 我怎样才能防止这种情况发生?如果在调用可用性时avail_bus的状态更改为true,则在单击“提交”时不应将其重新初始化为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



        }


         }
}

3 个答案:

答案 0 :(得分:1)

每次有页面请求时,都会创建该页面类的新实例来处理该请求。因此,任何字段都会重新初始化。

您可以在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



        }


         }
}

答案 1 :(得分:1)

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

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

访问它

另一个选项是在button1的click事件中再次调用Availability()作为第一行,以便在avail_bus变量中设置正确的值

答案 2 :(得分:1)

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

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

private static avail_bus = true;

Session State - 这使您可以在用户导航时存储和检索用户的值。

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

Control.ViewState - 获取状态信息字典,允许您跨同一页面的多个请求保存和恢复服务器控件的视图状态。

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