【发布时间】:2010-05-01 17:39:51
【问题描述】:
我有一个使用字典填充的列表框。当我使用以下代码遍历所选项目时,它始终只显示第一个项目被选中 - 即使第一个项目未被选中。
你遇到过这种情况吗?
你能帮忙吗?
当我使用字典进行绑定时会出现此问题。另一方面,通用列表可以正常工作。
private void PopulateListBox2()
{
List<string> subjectList = new List<string>();
subjectList.Add("Maths");
subjectList.Add("Science");
ListBox1.DataSource = subjectList;
ListBox1.DataBind();
}
如果值是唯一的,即使它也可以正常工作。但在我的情况下,值是相同的;唯一的关键变化。以下作品
private void PopulateListBox5()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo1");
resultDictionary.Add("Science", "Lijo2");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
^^^^^^^^^^^^^^^^^^^ 以下代码有问题。
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateListBox1();
ListBox1.SelectionMode = ListSelectionMode.Multiple;
}
}
private void PopulateListBox1()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo");
resultDictionary.Add("Science", "Lijo");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
MakeList1Items();
}
private void MakeList1Items()
{
string test = null;
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected == true)
{
if(string.IsNullOrEmpty(test))
{
test=item.Text;
}
else
{
test = test +", " + item.Text;
}
}
}
Response.Write(test);
}
}
谢谢
李乔
【问题讨论】:
-
这段代码出现在页面生命周期的什么地方?
-
此事件属于在按钮单击事件处理程序中调用的函数。
-
所以它在按钮的点击处理程序中?您可能希望使用更多周边代码来更新您的问题。这里真的没什么可做的。此外,请记住使用
010 101按钮或将代码缩进 4 个空格以使其格式正确。
标签: asp.net listbox selecteditem