简体   繁体   English

C#从列表框选择中显示文本框中的特定对象项

[英]C# displaying specific object items in a textBox from a listbox selection

I have a class Client, a Class Assignment and a static class Clients which has a static list. 我有一个Client类,一个Class Assignment和一个带有静态列表的静态Clients类。 The Client class constructor takes an Assignment object. Client类的构造函数采用一个Assignment对象。 Once the client and assignment object has been created, the Client is then added to the static list. 一旦创建了客户端和分配对象,便会将客户端添加到静态列表中。

My problem lies where the user then needs to be able to select any client in the listbox, and have the Assignments Description value displayed into a text box. 我的问题在于用户随后需要能够在列表框中选择任何客户端,并将“工作分配描述”值显示在文本框中。 How do i do this without getting an error telling me "Unable to cast object of type 'System.String' to type 'Rimu.Client'." 我如何做到这一点而又没有错误告诉我“无法将类型为'System.String'的对象强制转换为类型为'Rimu.Client'”。

private void clientListBox_MouseClick(object sender, MouseEventArgs e)
{
    if (clientListBox.SelectedItem != null)
    {
        Client current = (Client)clientListBox.SelectedItem;
        current.CurrentAssignment.Description = descriptionText.Text;
    }
}

any help would be greatly appreciated, Thanks in advance. 任何帮助将不胜感激,在此先感谢。

I would store your Client Objects in a Dictionary. 我会将您的客户对象存储在字典中。 The Key to each item in the Dictionary would the Name that you are putting in the ListBox. 字典中每个项目的键都是您要放在列表框中的名称。

Then, when an item in the ListBox is selected, you can get the object out of the dictionary. 然后,当在列表框中选择一个项目时,您可以从字典中获取该对象。

You are getting the error because you cannot cast a string to an arbitrary object. 由于无法将字符串强制转换为任意对象,因此出现错误。

Since you want to cast the SelectedItem directly from the ListBox you must add them directly to the list box, like so: 由于要直接从ListBox投射SelectedItem,因此必须将它们直接添加到列表框中,如下所示:

foreach (var client in Clients) 
{
  clientListBox.Add(client);
}

Now the Client objects are being stored in the ListBox, but the string displayed to the user on the winform (or wpf app, you didn't specify) will be the class name which isn't very meaningful to the user. 现在,Client对象存储在ListBox中,但是在winform(或wpf应用程序,您未指定)上显示给用户的字符串将是对用户而言意义不大的类名。

To fix this override the ToString() method of the Client class 要解决此问题,请覆盖Client类的ToString()方法。

public class Client
{
  // you've already written this

  public override string ToString() 
  {
    // construct a meaningful string here
    return string.Format("{0} {1}", this.FirstName, this.LastName);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM