如何获取列表框中项目的索引?

编程入门 行业动态 更新时间:2024-10-24 06:27:52
本文介绍了如何获取列表框中项目的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在像这样向ListBox添加项目:

I am adding items to a ListBox like so:

myListBox.Items.addRange(myObjectArray);

,我还想通过以下方法选择添加的一些项目:

and I also want to select some of the items I add by the following:

foreach(MyObject m in otherListOfMyObjects) { int index = myListBox.Items.IndexOf(m); myListBox.SelectedIndices.Add(index); }

但是index始终是-1.

是否有其他方法可以获取ListBox中的对象的索引?

Is there a different way to get the index of an object in a ListBox?

推荐答案

您应确保MyObject覆盖Equals(),GetHashCode()和ToString(),以便IndexOf()方法可以正确找到该对象.

You should make sure that MyObject overrides Equals(), GetHashCode() and ToString() so that the IndexOf() method can find the object properly.

从技术上讲,ToString()不需要覆盖相等性测试,但对于调试很有用.

Technically, ToString() doesn't need to be overridden for equality testing, but it is useful for debugging.

更多推荐

如何获取列表框中项目的索引?

本文发布于:2023-11-22 20:49:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618968.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   索引   项目   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!