Tyl*_*eat 6 c# asp.net listbox drop-down-menu
我有一个ListBox,我将ListItems添加到代码隐藏中.我遇到的问题是ListBox没有看到所选项目.我根据用户从DropDownList中选择的内容动态填充ListBox,因此DropDownList将AutoPostBack设置为true.我认为这是以某种方式导致问题.
我的SelectedIndexChanged方法,只要选择了DropDownList中的项,就会调用一个名为的方法PopulateListBox.以下是这些方法的样子:
protected void SelectedIndexChanged(object sender, EventArgs e)
{
string typeStr = type.SelectedItem.Text;
MyType = Api.GetType(typeStr);
PopulateListBox();
}
private void PopulateListBox()
{
listbox.Items.Clear();
foreach (PropertyInfo info in MyType.GetProperties())
listbox.Items.Add(new ListItem(info.Name));
}
Run Code Online (Sandbox Code Playgroud)
对于它的价值,这里是DropDownList和ListBox:
<asp:DropDownList runat="server" ID="type" width="281px" OnSelectedIndexChanged="SelectedIndexChanged" AutoPostBack="true" />
<asp:ListBox runat="server" ID="listbox" width="281px" height="200px" selectionmode="Multiple" />
Run Code Online (Sandbox Code Playgroud)
我想要做的是在单击提交按钮时添加一个字符串列表(作为所选项的字符串)作为会话变量.将List添加到会话后,该按钮将重定向到新页面.在调试器中,字符串列表在我将其添加到会话时是空的.
listbox.GetSelectedIndices() 没有回报.
更新
如果我没有在DropDownList中进行更改,我可以访问所选项目.ListBox最初是在页面加载时填充的,如果我进行选择,则会识别它们.如果我从DropDownList中选择一些内容并重新填充ListBox,则无法识别选择.
我的Page_Load方法只做两件事.它初始化我的Api变量和调用PopulateDropDown,如下所示:
private void PopulateDropDown()
{
foreach (Type t in Api.GetAllTypes())
type.Items.Add(new ListItem(t.Name));
string typeStr = type.Items[0].Text;
Type = Api.GetType(typeStr);
PopulateListBox();
}
Run Code Online (Sandbox Code Playgroud)
Dev*_*rke 13
问题是,你打电话PopulateDropDown()的每一个Page_Load(),它调用PopulateListBox(),从而清除列表框和重新填充它.通过清除列表框,您可以清除选择.
您需要更换您的来电PopulateDropDown()在Page_Load()用下面的代码.我认为你没有意识到的问题是每次回发都会加载页面 - 而在页面生命周期中,页面加载发生在事件之前.因此,通过选择下拉项,首先执行Page_Load()事件(间接执行LoadListBox方法,清除选择).下面的代码将填充下拉列表中的第一次加载页面只.在使用加载下拉方法的任何其他地方保持相同:
protected void Page_Load(object sender, EventArgs e)
{
// Do your API code here unless you want it to occur only the first
// time the page loads, in which case put it in the IF statement below.
if (!IsPostBack)
{
PopulateDropDown();
}
}
Run Code Online (Sandbox Code Playgroud)
IsPostBack返回一个布尔值,指示服务器端代码是否正在运行,因为页面是第一次加载("false")或作为回发("true").
正如我在其他地方所说的那样,请记住,具有多个所选值的潜在列表框必须以不同于具有单个选择潜力的列表框进行处理.不要参考listbox.SelectedItem,而是:
foreach (ListItem item in lbFullNames)
{
if (item.Selected)
{
// TODO: Whatever you are doing with a selected item.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17784 次 |
| 最近记录: |