65.9K
CodeProject is changing. Read more.
Home

WPF DataBinding

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.63/5 (9 votes)

Sep 12, 2007

CPOL
viewsIcon

93642

Data Binding to a combobox in WPF

Introduction

In this article, I will explain how to create a combobox and how to bind it to a dynamic datasource. Here I will use Northwind as the database and the table Categories for data.

Let's start with the XML (Extensible Application Markup Language) part of the code.

First create a combobox to list the categories:

<ComboBox Height="18" HorizontalAlignment="Right" Margin="0,92,17,0" Name="cmbCategory" 
VerticalAlignment="Top" Width="176" BorderBrush="#FFFFFFFF" SelectedIndex="0"/>

To bind the combobox to the datasource, we just need to set the ItemSource property to "{Binding}" like ItemsSource="{Binding}".

So here is the XAML for creating the bindable combobox.

<ComboBox Height="18" ItemsSource="{Binding}" 
    orizontalAlignment="Right" Margin="0,92,17,0" 
Name="cmbCategory" VerticalAlignment="Top" Width="176" 
    orderBrush="#FFFFFFFF" SelectedIndex="0"/> 

In the code behind, write the code to bind the data to the combobox.

I have created a private function to bind data to the combobox.

private void ListCategories()
     {
      sqlCon = new SqlConnection();
      sqlCon.ConnectionString = \\ConnectionString.

      cmd = new SqlCommand();
      cmd.Connection = sqlCon;
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = "SELECT * FROM Categories";

      sqlDa = new SqlDataAdapter();
      sqlDa.SelectCommand = cmd;

      ds = new DataSet();
      try
      {
          sqlDa.Fill(ds, "Category");
        
        //Binding the data to the combobox.
          cmbCategory.DataContext = ds.Tables["Category"].DefaultView;
        
        //To display category name (DisplayMember in Visual Studio 2005)
          cmbCategory.DisplayMemberPath = 
              ds.Tables["Category"].Columns["CategoryName"].ToString();
        //To store the ID as hidden (ValueMember in Visual Studio 2005)
          cmbCategory.SelectedValuePath = 
              ds.Tables["Category"].Columns["CategoryID"].ToString();
       }
       catch (Exception ex)
       {
           MessageBox.Show("An error occurred while loading categories.");
       }
       finally
       {
           sqlDa.Dispose();
           cmd.Dispose();
           sqlCon.Dispose();
       }
 }

Now we have written the code for binding the categories to the combobox but we haven't called it yet. So we will create a Loaded event (Load event in Visual Studio 2005) for the window.like Loaded="OnLoad". Add the Loaded event to the XAML:

<Window
.......
Loaded="OnLoad"

>

Now write the code for the OnLoad handler.

private void OnLoad(object sender, System.EventArgs e)
{          
    ListCategories();
} 

DONE. Compile and RUN.

The complete code is given below.

XAML

<Window
.......
Loaded="OnLoad"

>

<Grid>

<ComboBox Height="18" SelectionChanged="cmbCategory_SelectionChanged" 
    ItemsSource="{Binding}" 
HorizontalAlignment="Right" Margin="0,92,17,0" Name="cmbCategory" 
    VerticalAlignment="Top" Width="176" 
BorderBrush="#FFFFFFFF" SelectedIndex="0"/>

</Grid>
</Window>

C#

private void OnLoad(object sender, System.EventArgs e) 
{          
    ListCategories();
}

private void ListCategories()
{
     sqlCon = new SqlConnection();
     sqlCon.ConnectionString = Common.GetConnectionString();

     cmd = new SqlCommand();
     cmd.Connection = sqlCon;
     cmd.CommandType = CommandType.Text;
     cmd.CommandText = "SELECT * FROM Categories";

     sqlDa = new SqlDataAdapter();
     sqlDa.SelectCommand = cmd;

     ds = new DataSet();
     try
     {
         sqlDa.Fill(ds, "Category");

         DataRow nRow = ds.Tables["Category"].NewRow();
         nRow["CategoryName"] = "List All";
         nRow["CategoryID"] = "0";
         ds.Tables["Category"].Rows.InsertAt(nRow, 0);

         //Binding the data to the combobox.
          cmbCategory.DataContext = ds.Tables["Category"].DefaultView;
        
        //To display category name (DisplayMember in Visual Studio 2005)
          cmbCategory.DisplayMemberPath = 
              ds.Tables["Category"].Columns["CategoryName"].ToString();
        //To store the ID as hidden (ValueMember in Visual Studio 2005)
          cmbCategory.SelectedValuePath = 
              ds.Tables["Category"].Columns["CategoryID"].ToString();

      }
      catch (Exception ex)
      {
          MessageBox.Show("An error occurred while loading categories.");
      }
      finally
      {
          sqlDa.Dispose();
          cmd.Dispose();
          sqlCon.Dispose();
      }

 }

History

  • 12th September, 2007: Initial post