[英]How do I populate a listbox based on a selected item from another listbox?
[英]Populate second listbox based on the selected value from first listbox
我有2个清单方块。
<asp:ListBox ID="ListBox_Region" runat="server"
DataTextField="arregion" DataValueField="arregion" AutoPostBack="True"
Height="96px"
Width="147px" DataSourceid="sqldatasource1"></asp:ListBox>
<asp:ListBox ID="ListBox_Area" runat="server"
DataTextField="ardescript" DataValueField="ardescript"
AutoPostBack="True"
OnSelectedIndexChanged="ListBox_Area_SelectedIndexChanged"
Height="96px"
Width="147px" >
因此,当我从ListBox_Region中选择一个值时,以这种方式在ListBox_Area中更新相应的值:
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
ListBoxRegion_SelectedIndexChaged的事件写在页面加载中。
但是,问题出在初始页面加载上,默认情况下应该选择ListBox_Region的第一个值。 第二个列表框应更新为相应的值,但这应在选择的索引更改被触发之前发生。 所以,你能让我知道怎么做吗?
将ListBox_Region_SelectedIndexChanged
上的逻辑移至单独的方法,并在回发为false时从page_load
调用它。
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind ListBox_Region and set the first value as selected
...
//
BindAreaList();
}
}
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
BindAreaList();
}
protected void BindAreaList()
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.