I have a class Client, a Class Assignment and a static class Clients which has a static list. The Client class constructor takes an Assignment object. 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’.”
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.
Since you want to cast the SelectedItem directly from the ListBox you must add them directly to the list box, like so:
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.
To fix this override the ToString() method of the Client class