简体   繁体   中英

How to get listbox to display values C#

Need help trying to display values I have added to a listbox. I have researched several ways to add to a listbox. This was the latest attempt of mine, but I can't figure out how to display the "Netflix" and "Hulu". After debugging, the values are inside the listbox. I just can't see the text.

On a side note I am working on this to show a BASIC Observer Pattern. To show the changes in the code, I would like to display the results of subscribing to different providers. Thanks in advance guys!

public partial class MainWindow : Window
{
    List<string> myList = new List<string>();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void subscribeToNetflixButton_Click(object sender, RoutedEventArgs e)
    {
        Netflix netflix = new Netflix("Stir Crazy");
        Observer subscriberOne = new Observer();
        netflix.AddObserver(subscriberOne);
        myList.Add("Netflix");
        listBox.Items.Add(myList.ToArray());
    }

    private void subscribeToHuluButton_Click(object sender, RoutedEventArgs e)
    {
        Hulu hulu = new Hulu("Willy Wonka and the Chocolate Factory");
        Observer subscriberTwo = new Observer();
        hulu.AddObserver(subscriberTwo);
        myList.Add("Hulu");
        listBox.Items.Add(myList.ToArray());
    }
}

You should use AddRange with collections not Add :

public partial class MainWindow : Window
{
    List<string> myList = new List<string>();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void subscribeToNetflixButton_Click(object sender, RoutedEventArgs e)
    {
        Netflix netflix = new Netflix("Stir Crazy");
        Observer subscriberOne = new Observer();
        netflix.AddObserver(subscriberOne);
        myList.Add("Netflix");
        listBox.Items.AddRange(myList.ToArray());//This line should be changed
    }

    private void subscribeToHuluButton_Click(object sender, RoutedEventArgs e)
    {
        Hulu hulu = new Hulu("Willy Wonka and the Chocolate Factory");
        Observer subscriberTwo = new Observer();
        hulu.AddObserver(subscriberTwo);
        myList.Add("Hulu");
        listBox.Items.AddRange(myList.ToArray());//And this line
    }
}

BTW: If you're using WPF though you have to add your own AddRange (it is not available by default), through looping over the collection inside an extension method for example, or outside if you don't need the functionality many times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM