如何使用C#列出列表框中的类对象?

jM2*_*.me 2 c# listbox winforms

我有一个自定义类

class RouteStop
{
    public int number;
    public string location;
    public string street;
    public string city;
    public string state;
    public string zip;

    public RouteStop(int INnumber, string INlocation, string INstreet, string INcity, string INstate, string INzip)
    {
        this.number = INnumber;
        this.location = INlocation;
        this.street = INstreet;
        this.city = INcity;
        this.state = INstate;
        this.zip = INzip;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个列表,我存储RouteStop项目

private List<RouteStop> routeStops = new List<RouteStop>();
Run Code Online (Sandbox Code Playgroud)

我想要存档的是将列表中的所有对象加载到列表框中.到目前为止它确实是它的工作,但它只是将对象名称写入如下所示的列表而不是实际地址在此输入图像描述

如何让它显示让我们说数字+位置+街道+城市而不是对象名称?

同样在将来,我将需要添加OnSelect事件来打开一个新窗口来编辑每个对象的数据.我如何传递有关选择哪个项目的信息?

补充: 非常感谢大家.每个答案都有帮助 所以我到目前为止所做的是将数据源更改为列表,覆盖ToString方法以在列表中显示完整地址,将新项目添加到具有唯一ID的RouteStop并将DisplayMember设置为uniqe id以便我将来可以通过id访问所选项目同样.

再次非常感谢你

Hen*_*man 8

有几种选择,

  • 覆盖ToString(),但这在任何地方都有效.也许有用.
  • 插入格式化的字符串,然后通过索引找回对象
  • 使用DataSource,DisplayMember和ValueMember - 您需要一个伪数字+位置+街道+城市的属性,并将其用作显示成员
  • 处理ListBox格式事件

最后一个可能是最实用的.ListBox.Items仍然是RouteStops,您可以根据需要创建字符串.

Format事件的内部结构如下:

RouteStop rs = e.Item as RouteStop;
string s = ... // use rs to create a nice string 
e.Value = s;
Run Code Online (Sandbox Code Playgroud)

要在以后的"双击"事件中使用它,只需执行此操作,其中url只是RouteStop的属性.

private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    Process.Start("iexplore.exe",((RouteStop)listBox1.SelectedItem).url);
}
Run Code Online (Sandbox Code Playgroud)