Click here to Skip to main content
Licence CPOL
First Posted 11 Sep 2007
Views 59,760
Bookmarked 19 times

WPF DataBinding

By | 11 Sep 2007 | Article
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

License

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

About the Author

Sreejith Thathanattu

Software Developer

India India

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThanks. PinmemberURFukd2:00 14 Oct '08  
QuestionHow to add Combox Item to combobox with Data Binding Pinmemberrakesh chimanpure20:54 19 Jun '08  
GeneralThanks PinmemberTMags4:13 3 Oct '07  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 12 Sep 2007
Article Copyright 2007 by Sreejith Thathanattu
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid