目录
Getting selected item from a WPF combobox populated by data from an access database
c#wpfwindowsxamlms-access
浏览量:6
编辑于:2023-04-12 22:24:23

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?

解决方案:

you can do this way simply:

string value =ComboBoxOrg.SelectedItem.Text();

or

string Value="";
if(ComboBoxOrg.SelectedIndex>=0) 
  Value=((ComboBoxItem)ComboBoxOrg.SelectedItem).Content.ToString();