473,395 Members | 1,458 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,395 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 33540
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.