473,320 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

how to add DataGridComboBoxColumn to datagrid in wpf?

I'm using a DataSet and DataGrid.

I bind them like this :
Expand|Select|Wrap|Line Numbers
  1.  ObjDataAdapter.Fill(ObjDataSet);
  2.  ObjDataGrid.ItemsSource = ObjDataSet.Tables[0].DefaultView;
  3.  
I want to add DataGridComboBoxColumn to ObjDataGrid and show a ComboBox in each row . how can I do that in wpf?
Oct 27 '10 #1

✓ answered by Aimee Bailey

In WPF the solution is a little bit more complex, however with a bit of patience you'll find it's wonderful. Here is an example on how to use it...

XAML:
Expand|Select|Wrap|Line Numbers
  1. <Window x:Class="WpfApplication1.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         xmlns:core="clr-namespace:System;assembly=mscorlib"
  5.         xmlns:local="clr-namespace:WpfApplication1"
  6.         Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
  7.  
  8.     <Window.Resources>
  9.         <ObjectDataProvider x:Key="RecordValues" MethodName="GetValues"
  10.                             ObjectType="{x:Type core:Enum}">
  11.             <ObjectDataProvider.MethodParameters>
  12.                 <x:Type Type="local:RecordValues"/>
  13.             </ObjectDataProvider.MethodParameters>
  14.         </ObjectDataProvider>
  15.     </Window.Resources>
  16.  
  17.  
  18.     <Grid>
  19.         <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}"
  20.                   Margin="10" Name="dataGrid1">
  21.             <DataGrid.Columns>
  22.                 <DataGridComboBoxColumn Header="Combo" Width="300"
  23.                      SelectedItemBinding="{Binding Values}" 
  24.                      ItemsSource="{Binding Source={StaticResource RecordValues}}" />
  25.             </DataGrid.Columns>
  26.         </DataGrid>
  27.     </Grid>
  28. </Window>
  29.  
Notice that there are a few things here that need attention, first off, a ObjectDataProvider is requried in your XAML to be able to treat an enum in your project as visible to the combo column. There are one or two namespaces here that you will need to use also, such as xmlns:core and xmlns:local.

Once that is done, the rest is fairly simple, notice i created a DataGridComboBoxColumn in the XAML, and have used the binding properties SelectedItemBinding which should be a binding to the data that is to be displayed and changed, and ItemsSource which is a reference to the enum we adapted with the ObjectDataProvider.

Next is the code...

C#:
Expand|Select|Wrap|Line Numbers
  1.     public partial class MainWindow : Window
  2.     {
  3.         ObservableCollection<Record> Records = new ObservableCollection<Record>();
  4.  
  5.         public MainWindow()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void Window_Loaded(object sender, RoutedEventArgs e)
  11.         {
  12.             Records.Add(new Record());
  13.             Records.Add(new Record());
  14.             dataGrid1.DataContext = Records;
  15.         }
  16.     }
  17.  
  18.     public enum RecordValues
  19.     {
  20.         Apple,
  21.         Banana,
  22.         Coconut,
  23.         Dambul
  24.     }
  25.  
  26.     public class Record
  27.     {
  28.         private RecordValues _value = RecordValues.Apple;
  29.         public RecordValues value 
  30.         {
  31.            get { return _value; } set { _value = value; } 
  32.         }
  33.     }
  34.  
For the purposes of this answer, it's not sensible to include data retrieved from a database, instead i've opted for a custom class, it's important to note that you must use properties, just having a public variable inside a class is not good enough, and it's just plain good practice. Here you can also see the little enum i created, this can however be collection of strings if you wished.

Lastly, remember to use the DataContext property to fill your grid rather than ItemsSource.

Hope this helps!

Aimee Bailey.

3 33502
Aimee Bailey
197 Expert 100+
In WPF the solution is a little bit more complex, however with a bit of patience you'll find it's wonderful. Here is an example on how to use it...

XAML:
Expand|Select|Wrap|Line Numbers
  1. <Window x:Class="WpfApplication1.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         xmlns:core="clr-namespace:System;assembly=mscorlib"
  5.         xmlns:local="clr-namespace:WpfApplication1"
  6.         Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
  7.  
  8.     <Window.Resources>
  9.         <ObjectDataProvider x:Key="RecordValues" MethodName="GetValues"
  10.                             ObjectType="{x:Type core:Enum}">
  11.             <ObjectDataProvider.MethodParameters>
  12.                 <x:Type Type="local:RecordValues"/>
  13.             </ObjectDataProvider.MethodParameters>
  14.         </ObjectDataProvider>
  15.     </Window.Resources>
  16.  
  17.  
  18.     <Grid>
  19.         <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}"
  20.                   Margin="10" Name="dataGrid1">
  21.             <DataGrid.Columns>
  22.                 <DataGridComboBoxColumn Header="Combo" Width="300"
  23.                      SelectedItemBinding="{Binding Values}" 
  24.                      ItemsSource="{Binding Source={StaticResource RecordValues}}" />
  25.             </DataGrid.Columns>
  26.         </DataGrid>
  27.     </Grid>
  28. </Window>
  29.  
Notice that there are a few things here that need attention, first off, a ObjectDataProvider is requried in your XAML to be able to treat an enum in your project as visible to the combo column. There are one or two namespaces here that you will need to use also, such as xmlns:core and xmlns:local.

Once that is done, the rest is fairly simple, notice i created a DataGridComboBoxColumn in the XAML, and have used the binding properties SelectedItemBinding which should be a binding to the data that is to be displayed and changed, and ItemsSource which is a reference to the enum we adapted with the ObjectDataProvider.

Next is the code...

C#:
Expand|Select|Wrap|Line Numbers
  1.     public partial class MainWindow : Window
  2.     {
  3.         ObservableCollection<Record> Records = new ObservableCollection<Record>();
  4.  
  5.         public MainWindow()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void Window_Loaded(object sender, RoutedEventArgs e)
  11.         {
  12.             Records.Add(new Record());
  13.             Records.Add(new Record());
  14.             dataGrid1.DataContext = Records;
  15.         }
  16.     }
  17.  
  18.     public enum RecordValues
  19.     {
  20.         Apple,
  21.         Banana,
  22.         Coconut,
  23.         Dambul
  24.     }
  25.  
  26.     public class Record
  27.     {
  28.         private RecordValues _value = RecordValues.Apple;
  29.         public RecordValues value 
  30.         {
  31.            get { return _value; } set { _value = value; } 
  32.         }
  33.     }
  34.  
For the purposes of this answer, it's not sensible to include data retrieved from a database, instead i've opted for a custom class, it's important to note that you must use properties, just having a public variable inside a class is not good enough, and it's just plain good practice. Here you can also see the little enum i created, this can however be collection of strings if you wished.

Lastly, remember to use the DataContext property to fill your grid rather than ItemsSource.

Hope this helps!

Aimee Bailey.
Oct 27 '10 #2
Thanks dear Aimee Bailey, your solution was very useful.
I solve this problem like this:

Expand|Select|Wrap|Line Numbers
  1. public List<string> comboboxItemsSource { get; set; }
  2.  
  3. private void BtnSetting_Click(object sender, RoutedEventArgs e)
  4. {
  5. comboboxItemsSource = new List<string>() { "A", "B", "C", "D" };
  6. DataGridComboBoxColumn ObjDataGridComboBoxColumn= new DataGridComboBoxColumn();
  7.  
  8. ObjDataGridComboBoxColumn.ItemsSource = comboboxItemsSource;
  9.  
  10. ObjDataGridComboBoxColumn.Header = "zzz";
  11. ObjDataAdapter.Fill(ObjDataSet);
  12. ObjDataGrid.ItemsSource= ObjDataSet.Tables[0].DefaultView;
  13. ObjDataGrid.Columns.Add(ObjDataGridComboBoxColumn);
  14. }
It works very good. But has some problem:
When i add The ObjDataGridComboBoxColumn , ObjDataGrid shows It at first of columns.
When i look at ObjDataGrid[Counter].Columns.Count property it's equal to 1 so I can't use ObjDataGrid[Counter].Columns.Move(); method to move it.
So I decided to follow your guide and use ObjDataGrid.DataContext property.
I find this http://abitsmart.com/tag/wpf-binding...d-to-datatable
and it's solution is this :

Setting the DataContext to the table and then binding ItemsSource to the DataContext
XAML,
Expand|Select|Wrap|Line Numbers
  1. <Window x:Class="WpfDemo.Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:dtgrd=
  5. "clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"
  6.     Title="Window1" Height="400" Width="400">
  7.     <Grid  Name="_maingrid">
  8.         <dtgrd:DataGrid
  9.                          x:Name="_dataGrid"
  10.                          ItemsSource="{Binding Path=.}"
  11.                          ColumnHeaderHeight="25"
  12.                          AutoGenerateColumns="True"
  13.                               >
  14.         </dtgrd:DataGrid>
  15.     </Grid>
  16. </Window>
C#Code

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Data;  
  15.  
  16. namespace WpfDemo
  17. {
  18.     /// <summary>
  19.     /// Interaction logic for Window1.xaml
  20.     /// </summary>
  21.     public partial class Window1 : Window
  22.     {
  23.         private DataSet _ds;  
  24.  
  25.         public Window1()
  26.         {
  27.             InitializeComponent();
  28.         }  
  29.  
  30.         protected override void OnInitialized(EventArgs e)
  31.         {
  32.             base.OnInitialized(e);  
  33.  
  34.             ds = new DataSet();
  35.             DataTable dt = new DataTable();
  36.             ds.Tables.Add(dt);  
  37.  
  38.             DataColumn cl = new DataColumn("Col1", typeof(string));
  39.             cl.MaxLength = 100;
  40.             dt.Columns.Add(cl);  
  41.  
  42.             cl = new DataColumn("Col2", typeof(string));
  43.             cl.MaxLength = 100;
  44.             dt.Columns.Add(cl);  
  45.  
  46.             DataRow rw = dt.NewRow();
  47.             dt.Rows.Add(rw);
  48.             rw["Col1"] = "Value1";
  49.             rw["Col2"] = "Value2";  
  50.  
  51.             _datagrid.DataContext = ds.Tables[0];
  52.         }
  53.     }
  54. }
/////////////////////////////////////////////////////////
It works very good. But my problem is that I can't use xaml and I should do all the things in c# code.
How can I do something like ItemsSource="{Binding Path=.}" in c# code?
Excuse me because of my poor English it's not my native language.
Oct 28 '10 #3
your solution is ok. how can i show one of my datagridcombobox items at first ?
and when i choose an item from combobox and go to next row combobox shows me nothing. how can i fix that?
Oct 29 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Christopher | last post by:
I am attempting to put a combo box into a datagrid, I have created a component class called DataGridComboBoxColumn.cs */ I keep getting these 2 errors when I run the project : 1)Object reference...
2
by: Michael Schindler | last post by:
why see my combobox not in datagrid with values(offen, closed) not to column the 5? Please help me! This is my first combobox and i have no idea what i can to do. My source:
3
by: Bill C. | last post by:
Hello, I know this has been discussed a lot already because I've been searching around for information the last few weeks. I'm trying to implement a DataGridComboBoxColumn class. I've found...
3
by: Kevin | last post by:
Hi Al I want to add two combobox columns in my datagrid. the one combobox column must be bound to the same datasource that the datagrid is, and the other combobox I just want to populate with a...
1
by: anonymous | last post by:
I've been trying to put a them, please help me out. Here's the major parts of my code: public Form1() { DataSet myDataSet = new DataSet("myDataSet"); DataTable testTable = new...
4
by: Randy | last post by:
Hello, I've got a Form which has a dataGrid on it. In one of the columns of the dataGrid, I've implemented a ComboBox using a DataGridComboBoxColumn Class. I've also over ridden the other...
5
by: jaYPee | last post by:
i have successfully added a combobox to my datagrid by setting their datasource from one of my table. here's my code... Dim grdColStyle6 As New DataGridComboBoxColumn() With grdColStyle6...
6
by: Ron L | last post by:
I have a dataset whose source is a SQL 2k stored procedure that I am trying to display in a datagrid. This datasource has 4 columns that I am interested in here, a text column and 3 value columns...
4
by: Anthony | last post by:
Hi Folks, I'm adding some columns to my datagrid which are of Combo Box type. I'm inheriting DataGridTextBoxColumn and doing all the usual stuff to get them populated. This is working fine. I...
0
by: Familjen Karlsson | last post by:
Hi I have downloaded some code and tried it and nothing happens with the datagrid. Explain what is wrong and what I have to do please. I have tried to Import the namespace Hamster and it didn't...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.