Results 1 to 3 of 3

Thread: [2.0] Binding a list to listbox

  1. #1

    Thread Starter
    Fanatic Member JPicasso's Avatar
    Join Date
    Aug 2001
    Location
    Kalamazoo, MI
    Posts
    843

    [2.0] Binding a list to listbox

    Is there a way to Bind a list (or bindinglist) of structs to a listbox?


    When I set my datasource, I get "WindowsTestingGrounds.scData"
    I am unable to alter the .DisplayMember prop of the listBox to be anything relevant.

    Here is a simple example.
    I'd like to see a list of all the first names.
    Code:
    namespace WindowsTestingGrounds
    {
        public partial class FormBindList : Form
        {
            public FormBindList()
            {InitializeComponent();}
                    
            BindingList<scData> scdataList = new BindingList<scData>();
    
            private void button1_Click(object sender, EventArgs e)
            {
                scdataList.Clear();
                scdataList.Add(new scData("Roger", "Moore"));
                scdataList.Add(new scData("Pierce", "Bronsen"));
                scdataList.Add(new scData("Sean", "Connery"));
    
                listBox1.DataSource = scdataList;
                listBox1.DisplayMember = "scData.fname";
            }
        }
    
        struct scData
        {
            string fname;
            string lname;
            public scData(string F, string L)
            {
                fname = F;
                lname = L;
            }
        }
    
    }
    Merry Christmas

  2. #2
    Hyperactive Member
    Join Date
    May 2005
    Posts
    258

    Re: [2.0] Binding a list to listbox

    The problem is you are assigning the wrong DisplayMember. Use "key" instead since you are using a key/value pair type object. DisplayMember is which field to display. UseValue, not sure if a ListBox has this one, is which field to use as the value.
    Currently Using: VS 2005 Professional

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Binding a list to listbox

    Your problem is actually your structure declaration. You certainly can bind a list of structure instances to a ListBox but data binding only supports properties, not fields. You cannot bind your ListBox to the 'fname' and 'lname' fields. You must make the fields private and expose them via public properties. You can then bind to those properties.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width