Getting Selected Value of a Combobox

Getting selected value of a combobox

Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;

ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}

Get selected value from combo box in C# WPF

I have figured it out a bit of a strange way of doing it compared to the old WF forms:

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

Dim oleo As OLEObject
Dim clsComboEvent As CComboEvent

Set gclsComboEvents = New CComboEvents

For Each oleo In Sheet1.OLEObjects
If TypeName(oleo.Object) = "ComboBox" Then
Set clsComboEvent = New CComboEvent
Set clsComboEvent.Cbx = oleo.Object
gclsComboEvents.Add clsComboEvent
End If
Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

C# - retrieve the selected value from a combobox

SelectedValue will return the value of the property defined in ValueMember, SelectedItem will return the entire object that is selected, if you want to get another value other than your SelectedValue you will have to cast as the object in your ComboBox then you can access your Name property.

string temp = (cboTypeOfMaterial.SelectedItem as YourObjectType).Name;

getting selected value of Combobox python

this worked for me :

def create(self):
print(self.geo)
strgeo="\n".join(str(x) for x in self.geo)

print(strgeo)
city = ttk.Combobox(gui, textvariable=self.stringGeo, state="readonly",width=30)
city.config(values=strgeo)
city.pack()
city.bind("<<ComboboxSelected>>",self.selectedCity)

def selectedCity(self,event):
selected=self.stringGeo.get()

How to retrieve selected value of combobox (not text)

You have assigned a ComboboxItem instance to the Items collection of the ComboBox, so a ComboboxItem is returned by SelectedItem (or SelectedValue):

ComboboxItem item = accessLevelCombobox.SelectedItem as ComboboxItem;

if (item != null && item.Value == "SSLVPN,anothergroup,andanother")
{
}

ComboBox get selected value independently of selection method

This works pretty well for me if I set the AutocompleteMode to Append or SuggestAppend and the AutoCompleteSource to ListItems:

private void ComboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (dependenciesData.dependencyDic
.TryGetValue((string)comboBox3.SelectedItem, out string[] values)) {

comboBox4.DataSource = values;
comboBox4.SelectedIndex = 0;
}
}

Setting the AutocompleteMode to Suggest does not work.

If it is ensured that the dictionary contains all combo box entries as key. Then this can be simplyfied a litte bit:

if (comboBox3.SelectedIndex >= 0) {
comboBox4.DataSource =
dependenciesData.dependencyDic[(string)comboBox3.SelectedItem];
comboBox4.SelectedIndex = 0;
}

I set the data source of comboBox3 like this:

comboBox3.DataSource =dependenciesData.dependencyDic.Keys
.OrderBy(x => x)
.ToList();

The easiest way to allow the user entering only allowed values is to set the DropDownStyle of combo box to DropDownList. With this setting, he cannot edit the combo box text anymore, however he still gets autocomplete suggestions.


A few notes to your coding style:

  • Nested if-statements if (condition1) { if (condition2) { ... } } can be written as if (condition1 && condition2) { ... }.
  • Instead of adding individual items to a combo box with Items.Add(...), you can set the ComboBox.DataSource Property to a list or array.
  • If the combo box contains strings, you can simply cast the SelectedItem property to string instead converting it to string. (There is no conversion to be done since it is already a string that is statically typed as object).
  • You are testing whether the combo box items contain a text which is a O(n) operation. You can do this more efficiently by performing the test on the dictionary containing the same texts as keys, which is a O(1) operation.
  • You use the redundant string interpolation $"{comboBox3.Text}". Simply using comboBox3.Text yields the same result.

Getting selected values from combobox

I'm not sure why you are doing what you are doing, but (assuming I am understanding you), if I were going to do it, my solution would look something like (for three combo boxes):

    var comboBoxes = new List<ComboBox> { comboBox1, comboBox2, comboBox3 };
var results = new Dictionary<string, string>();
foreach (var comboBox in comboBoxes)
{
if (comboBox.SelectedIndex != -1)
{
results.Add(comboBox.Name, comboBox.SelectedItem.ToString());
}
}

Get selected value from comboBox

You may use SelectedValue or SelectedItem property but also you have to check whether the returned value is null or not.

If you bind the DataTable then the SelectedItem property return DataRowView.

DataRowView row = (DataRowView)accCollection.SelectedItem;
if(row!=null)
{
MessageBox.Show(row[0] + " " + row[1]);
}

In case of SelectedValue,

var result = accCollection.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}

EDIT:

Code in Form_Load event:

private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("A1", typeof(int));
dt.Columns.Add("A2");
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");

comboBox1.DataSource = dt;
comboBox1.DisplayMember = "A2";
comboBox1.ValueMember = "A1";
}

Code in Click handler of Button:

var result = comboBox1.SelectedValue;
if (result != null)
{
MessageBox.Show(result.ToString());
}

DataRowView row = (DataRowView)comboBox1.SelectedItem;
if (row != null)
{
MessageBox.Show(row[0] + " " + row[1]);
}


Related Topics



Leave a reply



Submit