Posted by: Zeeshan Amjad | October 13, 2011

ComboBox in DataGrid


I came across a question that how to display combo box in Data Grid. It is not different than displaying it in ListView we saw here. Similarly we have need to make a nested data structure first. Here is our data class.

Code Snippet
public class State
{
    public string Name
    { get; set; }

    public string TimeZone
    { get; set; }

    public string Capital
    { get; set; }

    public ObservableCollection<string> Cities
    { get; set; }
}

 

Then we populate it with some data.

Code Snippet
states.Add(new State()
{
    Name = "Maryland",
    Capital = "Annapolis",
    TimeZone = "Eastern",
    Cities = new ObservableCollection<string>() { "Frederick", "Baltimore", "Rockville"}
});

states.Add(new State()
{
    Name = "Taxes",
    Capital = "Austin",
    TimeZone = "Central",
    Cities = new ObservableCollection<string>() { "Houston", "Dallas", "San Antonio" }
});

states.Add(new State()
{
    Name = "Utah",
    Capital = "Salt Lake City",
    TimeZone = "Mountain",
    Cities = new ObservableCollection<string>() { "West Valley City", "Provo", "West Jordon" }
});

states.Add(new State()
{
    Name = "California",
    Capital = "Sacramento",
    TimeZone = "Pacific",
    Cities = new ObservableCollection<string>() { "Los Angeles", "San Fransisco", "San Diego" }
});

 

Then we define DataGridTemplateColumn and define data template for our column where we want to display the combo box. Here is a piece of XAML code for this.

Code Snippet
<DataGridTemplateColumn Header="Cities" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox Margin="2" ItemsSource="{Binding Cities}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

 

Rest of the code is very simple. Here is our complete C# code of the program.

Code Snippet
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfDataGridCombo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<State> states = new ObservableCollection<State>();

        public MainWindow()
        {
            InitializeComponent();

            states.Add(new State()
            {
                Name = "Maryland",
                Capital = "Annapolis",
                TimeZone = "Eastern",
                Cities = new ObservableCollection<string>() { "Frederick", "Baltimore", "Rockville"}
            });

            states.Add(new State()
            {
                Name = "Taxes",
                Capital = "Austin",
                TimeZone = "Central",
                Cities = new ObservableCollection<string>() { "Houston", "Dallas", "San Antonio" }
            });

            states.Add(new State()
            {
                Name = "Utah",
                Capital = "Salt Lake City",
                TimeZone = "Mountain",
                Cities = new ObservableCollection<string>() { "West Valley City", "Provo", "West Jordon" }
            });

            states.Add(new State()
            {
                Name = "California",
                Capital = "Sacramento",
                TimeZone = "Pacific",
                Cities = new ObservableCollection<string>() { "Los Angeles", "San Fransisco", "San Diego" }
            });

            DataContext = states;
        }
    }

    public class State
    {
        public string Name
        { get; set; }

        public string TimeZone
        { get; set; }

        public string Capital
        { get; set; }

        public ObservableCollection<string> Cities
        { get; set; }
    }
}

 

Here is complete XAML code of our program.

Code Snippet
<Window x:Class="WpfDataGridCombo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="Combo Box in Daga Grid" Height="300" Width="400">
    <Grid>
        <DataGrid Margin="5" ItemsSource="{Binding}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Capital" Binding="{Binding Capital}"/>
                <DataGridTextColumn Header="Time Zone" Binding="{Binding TimeZone}"/>
                <DataGridTemplateColumn Header="Cities" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Margin="2" ItemsSource="{Binding Cities}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

 

This is an output of the program.

ComboInGridOutput

Advertisements

Responses

  1. Hi Zeeshan,

    I have alternative implementation in my mind I have change ur DataTemplate

    Now we just need to create ObservableCollection list property for cities in MainWindow.cs.

    your status Model will look like this

    public class State
    {
    public string Name
    { get; set; }

    public string TimeZone
    { get; set; }

    public string Capital
    { get; set; }

    public string City
    { get; set; }
    }

    cheers

    Wasim khan

    • Can you please explain it little bit more detail. I selected the ObservableCollection property type, because it will be natural for me to move in MVVM model by introducing ViewModel class rather than creating ObservableCollection as a seperate field (or property / local variable) in view class.

  2. if I want to save the change made back to a DataBase how to do it

    • I guess it should be the responsibility of your model class or the data adaptor class that fatched data from the database and post it back there. In this simple example I tried to avoid all such complication and focus only on how to display the data in the form of ComboBox in DataGrid. This should be same, but you might have to change the model to use some library, LINQ, DataEntity Framework, ORM (Object Retional Model such as NHibernate) etc.

      Regards
      Zeeshan Amjad

  3. when i put this xaml showing me errror assembly reference missing…i used vs2008 with wpf toolkit…..can u suggest me wt i would do

    • Can you please show me the error message so I will be able to suggest you something.

      Regards
      Zeeshan Amjad


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: