Ronan Ronan - 1 year ago 44 Question

Read Items From Text File Into Combo Box, VB, WPF

I am currently developing a WPF application using the Visual Basic language, I am looking to read a list of items from a standard text file (ObjectNames.txt, stored within the same directory as the application) and enter them into a combo box. I have been looking for a solution and have found only answers that call the "AddRange" method, a method that is used in Windows Forms applications but not WPF applications.

If anyone could tell me how I can accomplish this, I am still quite new to Visual Basic and WPF applications. I would also like the combo box to be cleared before the file is written into it as its contents depends upon the output of another control, I believe I can do this using "comboBox.Items.Clear" just before the read operation.

Any answers greatly appreciated, thank you!

Answer Source

I suggest that you divide your task into two parts, to make each simple.

1) Load your items from the file and create a collection of them, such as a List of strings, or a List of instances of any class that overrides the ToString method to yield the object in the way you want it to show within your ComboBox. Thus, this will be the same regardless of whether you're using Forms or WPF.

2) Bind your WPF ComboBox to this list, using standard MVVM binding. Here is an over-simplified, contrived example:

In your view-model class..

public List<string> MyItems
        if (_myItems == null)
            // Create the _myItems list from your data-file here.
        return _myItems;

private List<string> _myItems;

Now in your XAML (or your code-behind), set the DataContext of your XAML object to your view-model class instance, and bind the ItemsSource of your ComboBox thusly:

<ComboBox Name="cbMyItems" ItemsSource="{Binding MyItems}" ..

I hope this helps. WPF does take just a bit to get started, mentally, but it will quickly feel very simple and versatile to you. Best of wiehs Ronan.

James Hurst

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download