我使用asp dropbox并从数据库中填充dropbox。但是当点击按钮时dropbox的值发生变化因为按钮调用第一个pageload代码调用的when事件而在pageload中我从数据库中填充了dropbox 代码是
protected void Page_Load(object sender, EventArgs e)
{
var q = from u in db.tbl_Subject select u;
Paper_Subject.DataSource=q.ToList();
Paper_Subject.DataTextField = "Subject_Name";
Paper_Subject.DataValueField = "Subject_Id";
Paper_Subject.DataBind();
for (int i = 0; i <= 12;i++)
{
if(i<10)
Paper_Duration_Hour.Items.Add("0"+i.ToString());
else
Paper_Duration_Hour.Items.Add(i.ToString());
}
for (int i = 0; i <= 60; i=i+5)
{
if(i<10)
Paper_Duration_Minute.Items.Add("0"+i.ToString());
else
Paper_Duration_Minute.Items.Add(i.ToString());
}
}
protected void SaveData()
{
int PaperDurationHour;
int PaperDurationMinute;
int TeacherId;
int SubjectId;
tb.Paper_Name = PaperName.Text;
if (int.TryParse(Paper_Duration_Hour.Text, out PaperDurationHour))
{
tb.Paper_Time_Hours = PaperDurationHour;
}
if (int.TryParse(Paper_Duration_Minute.Text, out PaperDurationMinute))
{
tb.Paper_Time_Minute = PaperDurationMinute;
}
string s1;
s1 = Paper_Subject.SelectedItem.Text;
var q = from u in db.tbl_Subject where u.Subject_Name.Equals(s1) select u;
if (q.Count() > 0)
{
SubjectId = q.FirstOrDefault().Subject_Id;
tb.Subject_Id = SubjectId;
}
if (int.TryParse(Session["TeacherID"].ToString(), out TeacherId))
{
tb.Teacher_Id = TeacherId;
}
db.tbl_Paper.Add(tb);
db.SaveChanges();
}
}
当按钮调用我想获取dropbox的选定值但每次因为pageload而得到第一个值
答案 0 :(得分:0)
我建议您在首次加载页面时以及更改某些数据时填充Dropbox。要在页面首次加载时填充Dropbox,您可以使用属性IsPostBack
,仅在首次加载页面时才为false,因此当您第一次加载页面时,语句(!IsPostBack)
将返回true页。因此你可以这样做:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//code here will be only executed the first time the page is loaded
var q = from u in db.tbl_Subject select u;
Paper_Subject.DataSource=q.ToList();
Paper_Subject.DataTextField = "Subject_Name";
Paper_Subject.DataValueField = "Subject_Id";
Paper_Subject.DataBind();
for (int i = 0; i <= 12;i++)
{
if(i<10)
Paper_Duration_Hour.Items.Add("0"+i.ToString());
else
Paper_Duration_Hour.Items.Add(i.ToString());
}
for (int i = 0; i <= 60; i=i+5)
{
if(i<10)
Paper_Duration_Minute.Items.Add("0"+i.ToString());
else
Paper_Duration_Minute.Items.Add(i.ToString());
}
}
//code here will be executed every time page loaded
}
,代码只会在您第一次加载页面时执行。