0

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
    • MyDataElement
      • firstName - string
      • lastName - string
    • MyDataManager
      • myDataList - List<MyDataElement>

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 type MyDataManager 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.

Community
  • 1
  • 1
Travis G
  • 13
  • 3

1 Answers1

0

You need to bind your View's DataContext with MyDataManager using Resources(In your case MyDataManager is considered as the ViewModel), see these anwsers. The VS GUI will be able to find your MyDataManager class members then. Hope it helps

Community
  • 1
  • 1
HichemSeeSharp
  • 3,240
  • 2
  • 22
  • 44