Results 1 to 3 of 3

Thread: [RESOLVED] Get info from listbox datasource

  1. #1
    Addicted Member
    Join Date
    Jan 10
    Location
    San Marcos, TX
    Posts
    177

    Resolved [RESOLVED] Get info from listbox datasource

    If I have a listbox and it's datasource is an array of objects. How can I get the text value of an element "title" of the selected object in the listbox? Title is one of the elements I created for the object.

    Each object in the datasource has various elements to it.

    Title
    Year

    Thanks in advance!

  2. #2
    Frenzied Member MattP's Avatar
    Join Date
    Dec 08
    Location
    WY
    Posts
    1,196

    Re: Get info from listbox datasource

    I'm going to assume you've got an array of your class and title is the property you want to get information from when an item is selected. In this case I'm setting it to a TextBox's Text property.

    Code:
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Book[] bookArray = new Book[] 
                {
                    new Book { title = "Title 1", isbn = "1234567890" },
                    new Book { title = "Title 2", isbn = "2345678901" },
                    new Book { title = "Title 3", isbn = "3456789012" },
                    new Book { title = "Title 4", isbn = "4567890123" },
                    new Book { title = "Title 5", isbn = "5678901234" }
                };
    
                BooksListBox.DataSource = bookArray;
                BooksListBox.DisplayMember = "title";
                BooksListBox.ValueMember = "isbn";
            }
    
            private void BooksListBox_SelectedIndexChanged(object sender, EventArgs e)
            {
                SelectedBookTextBox.Text = ((Book)BooksListBox.SelectedItem).title;
            }                                
        }                                    
                                             
        public class Book                    
    
        {
            public string title { get; set; }
            public string isbn { get; set; }
        }
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  3. #3
    Addicted Member
    Join Date
    Jan 10
    Location
    San Marcos, TX
    Posts
    177

    Re: Get info from listbox datasource

    Worked great thanks!

Posting Permissions

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