求助:ListBox的Contains方法无法生效,需判断ID存在后选中项
解决ListBox.Contains方法无法匹配ID的问题
我一眼就看出问题所在了——你现在用Contains传入的是int类型的值,但ListBox.Items集合里的元素其实是ListItem对象,默认的Contains方法是比较对象引用/类型是否完全一致,而不是去匹配ListItem的Value或Text属性,所以永远返回False,自然不会执行选中逻辑。
下面给你两种可行的解决思路,以及修正后的代码:
方法一:使用LINQ快速判断(推荐)
通过Cast<ListItem>()把Items集合转换成可查询的集合,然后用Any()方法检查是否存在Value等于目标ID的项:
Dim targetId As String = Session("SavedID").ToString() ' 处理ListBoxAccess If ListBoxAccess.Items.Cast(Of ListItem)().Any(Function(item) item.Value = targetId) Then ListBoxAccess.SelectedValue = targetId End If ' 处理ListBoxDenied If ListBoxDenied.Items.Cast(Of ListItem)().Any(Function(item) item.Value = targetId) Then ListBoxDenied.SelectedValue = targetId End If
方法二:遍历Items集合判断
如果你的项目不支持LINQ(比如较老的.NET版本),可以手动遍历每个ListItem进行比较:
Dim targetId As String = Session("SavedID").ToString() Dim isFoundInAccess As Boolean = False For Each item As ListItem In ListBoxAccess.Items If item.Value = targetId Then isFoundInAccess = True Exit For End If Next If isFoundInAccess Then ListBoxAccess.SelectedValue = targetId End If ' 同理处理ListBoxDenied Dim isFoundInDenied As Boolean = False For Each item As ListItem In ListBoxDenied.Items If item.Value = targetId Then isFoundInDenied = True Exit For End If Next If isFoundInDenied Then ListBoxDenied.SelectedValue = targetId End If
额外提示
- 注意把
Session("SavedID")转换成字符串,因为ListItem的Value属性本身是字符串类型,直接用字符串比较更稳妥,避免类型转换带来的问题。 - 其实你甚至可以直接尝试设置
SelectedValue,如果目标ID不存在,ListBox不会抛出异常,只会保持当前选中状态——如果你不需要额外的判断逻辑,这也是一种简化写法,但如果需要基于存在性做其他操作,还是建议先判断。
内容的提问来源于stack exchange,提问作者Kiel
相关产品推荐
相关产品推荐

