0

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''

Sahil Bora
  • 173
  • 1
  • 12

3 Answers3

0

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!

RPDF
  • 76
  • 8
0

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();
Welcor
  • 2,431
  • 21
  • 32
  • If I try this solution, my next line below of ap1 = (AccessPoint)selectedItem.Tag shows an error saying "String does not contain a definition for Tag" – Sahil Bora Dec 11 '19 at 23:05
  • @SahilBora the second example i gave returns the string. the question is, do you really need a string or what does your code need. The class "AccessPoint" does not look like it accepts a string. – Welcor Dec 12 '19 at 11:44
0

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;
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171