【发布时间】:2013-05-01 23:12:21
【问题描述】:
我在 C# 中有一个动态填充的列表框。我对列表框的 selectedindex_changed 有问题。每次它给出列表框中最后一项的值,而不是我选择的那个。我在另一个页面上的组合框也遇到了同样的问题。
我不知道为什么会这样。有谁知道我做错了什么?
首先,我创建一个新对象 Item 以将带有 ID 作为值的文本放入列表框中。
public class Item
{
public string Text { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Text;
}
}
在这里,我用文本和 ID 作为其值填充列表框。这工作正常,列表框被填满。
private void FormDeelnemers_Load(object sender, EventArgs e)
{
BLPersoon blPersoon = new BLPersoon();
DBOpdracht.PersoonDataTable personen = blPersoon.GetAllPersonen();
//Item item = new Item(); -> edit: delete this
foreach (DBOpdracht.PersoonRow persoon in personen)
{
Item item = new Item(); -> edit: add this here
item.Text = persoon.naam;
item.Value = persoon.ID;
listBoxPersonen.Items.Add(item);
}
}
这就是问题所在。它给出了列表框中最后一项的值,而不是我选择的那个。如何获得选中的?
private void listBoxPersonen_SelectedIndexChanged(object sender, EventArgs e)
{
int nummer = (listBoxPersonen.SelectedItem as Item).Value;
MessageBox.Show(nummer.ToString());
//MessageBox.Show(listBoxPersonen.SelectedItem.ToString()); -> same problem
}
【问题讨论】:
-
您是否有列表会导致选择时的回顾更改?或者您是否正在使用其他控件来导致回发?问题似乎是服务器实际从客户端接收到所选项目已更改的信息的时间。
-
不,您在 selectedindexchanged 中看到的代码是我目前获得的唯一代码,因为我偶然发现了这个问题。使用我的组合框时,我遇到了同样的问题,当弹出消息框时,选择了最后一个项目,但是当我关闭消息框时,再次选择了我选择的项目。所以我觉得这也很奇怪。
-
您的
Item实例化在FormDeelnemers_Load中的foreach循环之外。 -
太棒了,谢谢!我知道我已经尝试过其他一些事情,然后我总是得到第一个项目的价值,但现在它似乎工作正常。非常感谢!
-
@bmused,请将其发布为答案。
标签: c# listbox selecteditem selectedindexchanged