jayjay jayjay - 2 months ago 30
C# Question

Getting selected item from a WPF combobox populated by data from an access database

I have a combobox which is populated by data from an access database using the following code

public void BindComboBox(ComboBox ComboBoxOrg)
{
con.Open();
orgload = new OleDbCommand("SELECT organization_id, short_name FROM organization", con);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = orgload;
DataSet ds = new DataSet();
da.Fill(ds);
ComboBoxOrg.ItemsSource = ds.Tables[0].DefaultView;
ComboBoxOrg.DisplayMemberPath = ds.Tables[0].Columns["short_name"].ToString();
ComboBoxOrg.SelectedValuePath = ds.Tables[0].Columns["organization_id"].ToString();
con.Close();
}


The XAML UI code is

<ComboBox x:Name="ComboBoxOrg"
Width="308"
Height="40"
HorizontalAlignment="Left"
VerticalAlignment="Top"
FontSize="18"
Margin="0,0,0,100" Foreground="#FF666666"
ItemsSource="{Binding}"/>


I would like to GET THE SELECTED ITEM then use it to query a table(users) where its id is existing for example.

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\hcsshare\hcsshare.accdb; Persist Security Info=False");
cmd = new OleDbCommand("SELECT short_name FROM organization WHERE short_name='" + SELECTED_ITEM + "'", con);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count > 0)
{
}


The combobox is getting populated well, SO how do i get the SELECTED_ITEM from the combobox?

Answer

Your SelectedValuePath is organization_id whereas you are using the selectedValue to match with short_name, change your query condition to WHERE organization_id = selected_value_of_combobox.

Try this, not tested but definitely help you:

DataSet dataSet = new DataSet();
using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\hcsshare\hcsshare.accdb; Persist Security Info=False"))
{
    con.Open();
    OleDbCommand cmd = new OleDbCommand("SELECT short_name FROM organization WHERE organization_id=?", con);
    cmd.Parameters.Add("?", ComboBoxOrg.SelectedValue);

    using (var adapter = new OleDbDataAdapter(cmd)) 
    {
        adapter.Fill(data);
    }
}
if (dataSet.Tables[0].Rows.Count > 0)
{
    //your code goes....
}

Or if you really need to match the selectedValue with short_name,

use this query:

SELECT short_name FROM organization WHERE short_name=?

And add this as parameter:

cmd.Parameters.Add("?", ((ComboBoxItem)ComboBoxOrg.SelectedItem).Content.ToString());

Read more here.

Comments