Home > OS >  Select item in ComboBox using C#
Select item in ComboBox using C#

Time:09-17

people. Hope you are all well and safe.

Tricky situation here. I'm developing a desktop application that will act as a server and this application has a form where the user can set the server IP address and port to be used by the clients to access it.

What I thought during interface design was populating a ComboBox with all network interfaces and their respective IP addresses as the screenshot below shows.

enter image description here

To populate the ComboBox like this, I created a class that has three properties to store the IP address, the interface name and a description (mounted based on the previous two properties). This description is the property I set as the ComboBox DisplayMember. I also set the ComboBox ValueMember as the class IP address property.

When the user starts the application, it automatically loads the previously chosen settings (IP address, network interface name and port) from a JSON file. What I want to do is automatically set the ComboBox selected item based on the previously loaded configuration. My first approach was trying to use ComboBox's FindStringExact method (as shown in this answer) to find the description mounted by using the IP address and network interface name retrieved from the JSON file. This way I would have the proper value to store in the ComboBox's SelectedIndex property. However, FindStringExact is returning null to me, i.e., it is not finding the string.

Any thoughts on how I can find the index of the item that has the IP address and the network interface description recovered from the JSON file?

Appreciate any help.

Take care,

CodePudding user response:

I also set the ComboBox ValueMember as the class IP address property.

Assign the current IP address to the SelectedValue property and the corresponding item will be selected.

CodePudding user response:

What if you save the value you just selected and then when the combobox loads you just find the item that has the same text and just set its index pic

  • Related