0
votes

For my application, the user can select their preferred WiFi Access point they want to connect to using a Combobox. I'm trying to convert the selected item from the Combobox to a string value to be used with the SimpleWifi library

This is my attempted solution:

ComboBox selectedItem = (ComboBox)cbWifiname.SelectedItem;
AccessPoint ap = (AccessPoint)selectedItem.Tag;

An example code solution that I'm trying to follow

ListViewItem selecteditem = listView2.SelectedItems[0];
AccessPoint ap = (AccessPoint)selecteditem.Tag;

But the result of my attempted solution of using a combobox, a debugging error showing "Unable to cast object of type 'System.String to type 'System.Windows.Forms.Combobox''

3
SelectedItem is an object that can't be cast as combobox, this line is not correct ComboBox selectedItem = (ComboBox)cbWifiname.SelectedItem. what is the type of item you add there, is it a class or a string?Ashkan Mobayen Khiabani
It's strings that are getting populated into the comboboxSahil Bora
instead of string use a class, let me write an answer.Ashkan Mobayen Khiabani
I'm using a foreach loop to add the WiFi APs into the comboboxSahil Bora
foreach (AccessPoint ap in aps)Sahil Bora

3 Answers

0
votes

Please note that a combobox has a key, value pair, take a look on this How to set selected value from Combobox?

hope it helps!

0
votes

I think you cast the selectedItem to the type Combobox, while it actually is a ComboBoxItem. Maybe this will help:

ComboBoxItem selectedItem = ((ComboBox)cbWifiname).SelectedItem;

or if you really want to have it as a string:

string selectedItem = ((ComboBox)cbWifiname).SelectedItem.ToString();
0
votes

lets say that your items are a class like:

public class Wifi
{
     public string Name { get; set;}
     public AccessPoint { get; set;}
     //....
}

Make display member to be the property you want to show:

cbWifiName.DisplayMember = "Name";

Add to ComboBox like:

cbWifiName.Items.Add(new Wifi{ Name = "SomeName", AccessPint = somevalue});

Now you can get it like:

Wifi selected = (Wifi)cbWifiName.SelectedItem;
AccessPoint ap = selected.AccessPoint;