【发布时间】:2016-01-01 17:02:11
【问题描述】:
我正在制作在线表格。我一开始在我的代码中初始化了 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 。 我怎样才能防止这种情况发生?如果在调用可用性时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
}
}
}
【问题讨论】:
-
请分享按钮如何链接到事件
Button1_Click。 -
你试过用静态的吗?
-
静态不是最好的解决方案。使用视图状态。
-
@Rakin 你能解释一下原因吗?
-