C#, listbox, datasource, how to string a message into listbox while linked to datasource.

Interesting, I discovered it very hard to put string message on listbox since it create exception when listbox1.Items.Add() is applied because it tied to DataSource.

Is there a way to insert message string to listbox or it just not allowed.

What the real benefit in attaching object to Datasource via listbox?, have I missed something?

private void Form1_Load(object sender, EventArgs e)
	if (File.Exists("Configurations.xml"))
		configurations = DeserializeFromFile<List<ConfigurationX>>("Configurations.xml");
		if (configurations == null)
			configurations = new List<ConfigurationX>();
			for (int i = 0; i < 10; i++)
				configurations.Add(new ConfigurationX() { CompanyID = (uint)i, CompanyString = string.Format("ZMDI{0}", i) });

	if (configurations != null)
		listBox1.DataSource = configurations;
	listBox1.DisplayMember = "CompanyString";

Open in new window

Richard PayneChief Technology EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jacques Bourgeois (James Burger)PresidentCommented:
The advantage of using the DataSource is that all the work of filling the ListBox is done by the ListBox itself.

When you fill the ListBox with a list of ConfigurationX objects, it is not filled with a simple list of strings, it is filled with ConfigurationX objects. The DisplayMember is not used to tell the ListBox what to store in the ListBox, it is used to tell if which member/property of each ConfigurationX objects it should use for the display. Underneath, each entry in the ListBox is a ConfigurationX object.

The nice thing about that is that when the user makes a selection, you do not only get a string, but you can get to the whole ConfigurationX object underneath through the SelectedItem of the ListBox. Quite cool when you have worked with previous iterations of ListBoxes.

If by adding a message you mean something like a prompt to select something in the list, then you have 2 choices.

You can fill the ComboBox only with the strings that you want to display, which would enable you to add a string to it. When the user makes a selection, then lookup the equivalent entry in your list.

The second one is to add to your List a dummy ConfigurationX object that has the message in the CompanyString property, so that the message will appear along the real company names.
Richard PayneChief Technology EngineerAuthor Commented:
(1) Can you give example code with SelectedItem of the ListBox.
(2) How to select element within the class object to display information, for example Name:<> Address:<> or it not possible?

Jacques Bourgeois (James Burger)PresidentCommented:
CustomerCollection col = New CustomerCollection;

cboCustomers.DataSource = col;

Then, when the user makes a selection:

company = cboCustomers.Text;
id = (int) cboCustomers.SelectedValue;
address = ((CustomerCollection)cboCustomers.SelectedItem).Address;
contact = ((CustomerCollection)cboCustomers.SelectedItem).Contact;


Customer cust;
cust = ((CustomerCollection)cboCustomers.SelectedItem);
address = cust.Address;
contact = cust.Contact;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Athar SyedCommented:
When using a Class with listbox (or even DropDownList), you can specify what shows in the listbox by overriding the ToString() function of the class;

Public Class Customer
  Private m_lCustID As Long
  Private m_sCustName As String
  Private m_dtBirthDate As Date
  Private m_sCustAddress As String

  Public Property ID As Long
    Return m_lCustID
  End Get
  Set(value As Long)
    m_lCustID = value
  End Set
  End Property

  Public ReadOnly Age As Integer
    Return Today.Year - m_dtBirthDate.Year
  End Get
  End Property


  Public Overrides Function ToString() As String
    Return String.Format("{0} [{1}]", m_sCustName, m_lCustID)
  End Function

End Class

Open in new window

When you add an instance of this class in your listbox, the ListBox will display "Bob Minion [1]", "Steve Minion [2]", etc...

Adding and retrieving it as mentioned by our esteemed fellow @jacques.

Customer selectedCustomer = CType(MyListBox.SelectedItem, Customer)
' selectedCustomer.ID
' selectedCustomer.Name
' selectedCustomer.Address...

Open in new window

so on so forth. The same is applied for DropDownLists.
Richard PayneChief Technology EngineerAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.