我在我的asp页面中放置了一个下拉列表
<asp:DropDownList ID="authorList" runat="server"
OnSelectedIndexChanged="authorList_Changed" AutoPostBack="true"
></asp:DropDownList>
然后在codebehind中,我将它绑定到数据库中的一个字段,然后激活selectedindexchanged
protected void Page_Load(object sender, EventArgs e)
{
var a = (from s in p.Authors
select s.FirstName);
authorList.DataSource = p.Authors;
authorList.DataTextField = "Firstname";
authorList.DataValueField = "FirstName";
authorList.DataBind();
authorList.SelectedIndexChanged += new EventHandler(authorList_Changed);
var q = (from s in p.Authors
where s.FirstName.Contains("m")
select s);
Grid1.DataSource = q;
Grid1.DataBind();
// authorList.DisplayMember = "FirstName";
}
public void authorList_Changed(Object sender, EventArgs e)
{
//Author a = (Author) authorList.SelectedItem;
var a = authorList.SelectedValue;
var v = authorList.SelectedItem;
var q2 = (from s in p.Authors
from w in p.Payrolls
where authorList.SelectedValue == s.FirstName
where s.AuthorID == w.AuthorID
select w);
List<Payroll> d = q2.ToList();
if (d.Count > 0)
{
payroltextbox.Text = d.First().PayrollID.ToString();
//authorList.DataBind();
}
else
payroltextbox.Text = "";
// authorList.DataBind();
}
PublishingCompanyEntities p = new PublishingCompanyEntities();
但问题是当我的下拉列表值为1 2 3 4 ....... 1带默认值.......所以,当我选择4时它仍会在回发时返回1并返回文本框(payroltextbox)中的值与1相关联。你可以帮帮我.....
答案 0 :(得分:1)
这是因为您忘记在Page_Load中检查Page.IsPostback ...
每次加载页面时都会发生Page_Load,即使它是在回发时也是如此,因此在authorList_Changed事件之前重新填充第一个dropdown。这导致最重要的项目被重新选择。
请参阅Page Lifecycle。
并将您的数据绑定代码放在一个if语句中的Page_Load中,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
var a = (from s in p.Authors
select s.FirstName);
authorList.DataSource = p.Authors;
authorList.DataTextField = "Firstname";
authorList.DataValueField = "FirstName";
authorList.DataBind();
authorList.SelectedIndexChanged += new EventHandler(authorList_Changed);
var q = (from s in p.Authors
where s.FirstName.Contains("m")
select s);
Grid1.DataSource = q;
Grid1.DataBind();
// authorList.DisplayMember = "FirstName";
}
}