2

I'm trying to bind my database to a combobox ("ProjectComboBox"), and just can't seem to get it to to work. I've tried passing it through in XAML, as well as backend code, but Combobox is always blank. Any help would be appreciated.

SQL Server (local) database: "Database1"

Data source:(DataSet1); Table:(ProjectTable);

combobox name: "ProjectComboBox"

Here's my XAML code:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="850">
<Grid>
    <ComboBox x:Name="ProjectComboBox"
              ItemsSource="{Binding Path=ProjectTable}"
              DisplayMemberPath="ProjectName" 
              SelectedValuePath="RFIDirectory" 
              HorizontalAlignment="Left" 
              VerticalAlignment="Top" 
              Width="297" Height="26" 
              SelectionChanged="comboBox_SelectionChanged">
    </ComboBox>

And here's my backend code:

namespace WpfApplication1

public partial class MainWindow : Window
{
    public DataSet1 ProjectTable { get; set; }
    public MainWindow()
    {
        InitializeComponent();

    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ProjectComboBox.Items.Clear();

        SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Database1;Integrated Security=True");

        try
        {
            con.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        try
        {
            SqlDataAdapter ProjectTableTableAdapter = new SqlDataAdapter("SELECT * FROM PROJECTNAME", con);
            DataSet1 ds = new DataSet1();
            ProjectTableTableAdapter.Fill(ds, "t");

            ProjectComboBox.ItemsSource = ds.Tables["t"].DefaultView;
            ProjectComboBox.DisplayMemberPath = "ProjectName";
            ProjectComboBox.SelectedValuePath = "RFIDirectory";

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

    }
}

}

1
  • 1
    You're populating the combo box in comboBox_SelectionChanged, which will never fire because the combo box is empty so it can't be changed to anything. I hope that's a missing } after InitializeComponent();. Commented Jun 16, 2016 at 22:59

1 Answer 1

3
  1. You cannot bind directly to SQL Server table records. But, you can bind to a list of object that represents the table records.
  2. As @Paul Abbott mentioned, you must first initialize the combobox items once the form loads. Or an ugly way of doing this is adding a dummy record and once you select it the selection changed event will be raised then your code will execute.
  3. Don't do separate try-catch block for your connection open and sql data adapter. It is redundant.

  4. Use using statement on your sql connection to properly close and dispose after.

    public MainWindow()
    {
        InitializeComponent();
        UpdateItems(); // Maybe initialize here?
    }
    
    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ProjectComboBox.Items.Clear(); // Remove this. AFAIK, the selected item will be cleared.
        UpdateItems();
    }
    
    private void UpdateItems()
    {
        try
        {
            using(SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Database1;Integrated Security=True"))
            {
                con.Open();
                SqlDataAdapter ProjectTableTableAdapter = new SqlDataAdapter("SELECT * FROM PROJECTNAME", con);
                DataSet1 ds = new DataSet1();
                ProjectTableTableAdapter.Fill(ds, "t");
    
                ProjectComboBox.ItemsSource = ds.Tables["t"].DefaultView;
                ProjectComboBox.DisplayMemberPath = "ProjectName";
                ProjectComboBox.SelectedValuePath = "RFIDirectory";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        } 
    }
    
    <ComboBox x:Name="ProjectComboBox"
          ItemsSource="{Binding Path=ProjectTable}" // Not sure of what the impact will be by adding this because you have already defined the item source on your code-behind. I'd prefer you remove this and use XAML binding when you're following a design pattern like MVVM or MVPVM.
          DisplayMemberPath="ProjectName" 
          SelectedValuePath="RFIDirectory" 
          HorizontalAlignment="Left" 
          VerticalAlignment="Top" 
          Width="297" Height="26" 
          SelectionChanged="comboBox_SelectionChanged">
    </ComboBox>
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.