Click here to Skip to main content
15,886,724 members
Articles / Desktop Programming / Windows Forms
Article

WPF DataBinding

Rate me:
Please Sign up or sign in to vote.
1.63/5 (9 votes)
11 Sep 2007CPOL 93.1K   22   3
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:

XML
<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.

XML
<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.

C#
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:

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

>

Now write the code for the OnLoad handler.

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

DONE. Compile and RUN.

The complete code is given below.

XAML

XML
<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#

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThanks. Pin
URFukd14-Oct-08 2:00
URFukd14-Oct-08 2:00 
QuestionHow to add Combox Item to combobox with Data Binding Pin
rakesh chimanpure19-Jun-08 20:54
rakesh chimanpure19-Jun-08 20:54 
GeneralThanks Pin
TMags3-Oct-07 4:13
TMags3-Oct-07 4:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.