C# - getting value of SelectedItem in Windows Forms application
c#, combobox, selecteditem
Solution
I know I am a little late, but this works well:
int? nStoreNumber = cmbABSM.SelectedValue as int?;
if (nStoreNumber==null)
return;
Problem
I have a simple Windows Forms application (with an Access database) with a combobox (cmbStores) that is populated in the most simple way imaginable. Problem: I am unable to get the value of the selected item. Here is how I am populating this combobox: ``` // Variable declaration string strQueryStores = "SELECT StoreNumber FROM tblStoresAndRegion ORDER BY StoreNumber"; string strConnectionString = UtilityClass.GetConnectionString(); OleDbConnection connStores; OleDbDataReader readerStores = null; connStores = new OleDbConnection(strConnectionString); try { connStores.Open(); OleDbCommand sqlGetStores = new OleDbCommand(strQueryStores, connStores); cmbStore.Items.Clear(); cmbStore.Items.Add("All"); if (connStores != null) { readerStores = sqlGetStores.ExecuteReader(); if (readerStores.HasRows) { while (readerStores.Read()) { cmbStore.Items.Add (Convert.ToInt32(readerStores["StoreNumber"])); } } } cmbStore.SelectedIndex = 0; } catch (OleDbException oledblEX) { MessageBox.Show(oledblEX.Message); } finally { if (readerStores != null) readerStores.Close(); if (connStores != null) connStores.Close(); } ``` This is how I am trying to get the value of the selected item. ``` int nStoreNumber = Convert.ToInt32(cmbABSM.SelectedItem); ```