Click here to Skip to main content
Click here to Skip to main content

WPF DataBinding

, 11 Sep 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Sreejith Thathanattu
Software Developer
India India
No Biography provided

Comments and Discussions

 
GeneralThanks. PinmemberURFukd14-Oct-08 3:00 
QuestionHow to add Combox Item to combobox with Data Binding Pinmemberrakesh chimanpure19-Jun-08 21:54 
GeneralThanks PinmemberTMags3-Oct-07 5:13 

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.

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