How to use a ComboBox as a dropdown menu

mauede 221 Reputation points
2022-04-05T15:49:01.963+00:00

I have to show a list of strings (Trial names) that are fetched from a PostgreSQL database. The number of strings is only known at runtime.

I have implemented that through a ComboBox as follows:

[CODE=csharp]

  <ComboBox x:Name="TrialDB" Grid.Row="1" Grid.Column="1"  MinWidth="100"  Grid.ColumnSpan="21"

              ItemsSource="{Binding Path=MainWindow, Mode=OneWay}" 

              Background="Ivory" Margin="110,0,112,38" SelectionChanged="TrailDB_SelectionChanged" Selected="TrailDB_Selected" >

        <ComboBox.ItemTemplate>

            <DataTemplate>

                <Grid>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition Width="Auto"/>

                        <ColumnDefinition Width="*"/>

                    </Grid.ColumnDefinitions>

                    <TextBlock  x:Name="SQLDB" Text="{Binding trials}" Grid.Column="0" Padding="5,2" HorizontalAlignment="Center" FontFamily="Arial Black" FontSize="20" Width="250" />

                </Grid>

            </DataTemplate>

        </ComboBox.ItemTemplate>

    </ComboBox>[/CODE]

I also have to allow the user to select a string, from that ComboBox, that identifies a Trial name and upon this selection, I have to fetch another set of strings (Structure names) from the same PostgreSQL database and populate a ListBox.

My problem is to find two appropriate ComboBox events. One event to display the list of Trial names and another event to honor the user selection of a Trial name.

I thought to use the "SelectionChanged" event to deal with the selection of a Trial (a ComboBox item).

I need another event to awaken my code unit that fetches the Trial names from the PostgreSQL database and displays them as ComboBox items.

Although the Visual Studio list of ComboBox prefixed events contains "Selected", the compiler complains stating that "Selected" is not found for ComboBox.

Which event should I use?

If none of the ready-to-use events is appropriate for my goal, how can I create and handle my own ComboBox event?

Thank you so much for your attention.

Developer technologies | Windows Presentation Foundation
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,681 Reputation points Microsoft External Staff
    2022-04-06T03:06:51.963+00:00

    For the problem of populating a combobox with data from database based on the selected item of another combobox, you could try to refer to the code below.
    MainWindow.xaml:

     <ComboBox x:Name="categories" HorizontalAlignment="Left" Margin="52,194,0,0" VerticalAlignment="Top"  
                      Width="324" Height="43" FontSize="24" SelectionChanged="combo_app_SelectionChanged">  
            </ComboBox>  
    

    MainWindow.xaml.cs:

    using System;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Linq;  
    using System.Windows;  
    using System.Windows.Controls;  
      
    namespace ComboboxSelectedBind  
    {  
      public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
          BindComboBoxApp();  
        }  
        private void BindComboBoxApp()  
        {  
          string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;  
          string path = (System.IO.Path.GetDirectoryName(executable));  
          using (var con = new SqlConnection(@"constr"))  
          {  
            using (var command = new SqlCommand("SELECT CategoryId, Name FROM  [dbo].[Categories]", con))  
            {  
              SqlDataAdapter da = new SqlDataAdapter();  
              da.SelectCommand = command;  
              DataSet ds = new DataSet();  
              da.Fill(ds);  
              categories.ItemsSource = ds.Tables[0].DefaultView; ;  
              categories.DisplayMemberPath = "Name";  
              categories.SelectedValuePath = "CategoryId";  
              con.Close();  
            }  
          }  
        }  
        private void combo_app_SelectionChanged(object sender, SelectionChangedEventArgs e)  
        {  
          if (categories.SelectedItem != null)  
          {  
            var a = categories.SelectedValue;  
            var con = new SqlConnection(@"constr");  
            con.Open();  
            var command = new SqlCommand("SELECT COUNT(*) FROM  [dbo].[Categories] where CategoryId=@a", con);  
            command.Parameters.AddWithValue("@a", a);  
            var result = Convert.ToInt32(command.ExecuteScalar());  
            if (result > 0)  
            {  
              var cmd = new SqlCommand("SELECT ProductId, ProductName FROM [dbo].[Products] WHERE CategoryId like '" + categories.SelectedValue + "'  ", con);  
              SqlDataAdapter da = new SqlDataAdapter();  
              da.SelectCommand = cmd;  
              DataSet ds = new DataSet();  
              da.Fill(ds);  
              categories.ItemsSource = ds.Tables[0].DefaultView; ;  
              categories.DisplayMemberPath = "ProductName";  
              categories.SelectedValuePath = "ProductId";  
              con.Close();        }  
          }  
        }  
      }  
    }  
    

    The result:
    192067-image.png
    192164-image.png
    192122-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. mauede 221 Reputation points
    2022-04-06T07:54:44.813+00:00

    Sorry. I might not have been able to explain my problem correctly.

    I have only one ComboBox.
    The first click on the ComboBox must show the string fetched from a database.
    The second Click on the same ComboBox should indicate the item selected by the user from the ComboBox dropdown.
    So I need two distinguished events to handle the first and the second click.
    One of the useful ComboBox events is "SelectionChanged". This event can be used to deal with the user selection of an item.
    I am left with fetching the items from the database. I need an even that triggers my code that accesses the database. Is there an appropriate ComboBox event that I can use for this purpose?

    Thank you so much


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.