I feel like this is such a basic question, but I've spent 2 days trying to get it working with no success. Thank you for your time.
Problem Definition
- Visual Studio Express 2012 - Visual C# Windows Form Project
- Classes and Members
- MyForm (
Form
)- myListBox -
ListBox
- myListBox -
- MyDataElement
- firstName -
string
- lastName -
string
- firstName -
- MyDataManager
- myDataList -
List<MyDataElement>
- myDataList -
- MyForm (
Using the GUI, how can I bind myListBox
to myDataList
? More specifically, how do I go about instantiating MyDataManager
so that myListBox
gets populated with the list's values?
Steps Already Taken
I can create DataSources without trouble, but I cannot get the ListBox to show the contents of the underlying list. I have tried:
- Binding the ListBox to a standalone
MyDataManager
object - Creating a member in
MyForm
of typeMyDataManager
and binding the ListBox to that member
I couldn't get either to work. I've also tried changing the DisplayMember property to no avail.
Incidentally, I can get it to work properly by manually setting the DataSource (e.g., myListBox.DataSource = myDM.myDataList
) in the main method of MyForm
, but for future reference and my own edification I would love to learn how to do this through the GUI (if it's even possible).
Sample Code
public class MyDataElement
{
public string firstName { get; set; }
public string lastName { get; set; }
public override string ToString()
{
return firstName + " " + lastName;
}
}
public class MyDataManager
{
public List<MyDataElement> myDataList { get; set; }
// Constructor.
public MyDataManager()
{
myDataList = new List<MyDataElement>();
// Populate list for testing purposes.
myDataList.Add(new MyDataElement { firstName = "John", lastName = "Smith" });
myDataList.Add(new MyDataElement { firstName = "Jane", lastName = "Doe" });
}
}
In the main method of MyForm
:
// ...
myDM = new myDataManager();
InitializeComponents();
// ...
I have also tried reversing this order.