1

How can I center the text of ComboBox columns in a DataGridView?

The DataGrid is dynamically updated with columns of different types:

foreach (Fields field in fields)
                {
                    if (field.group.Count > 1)
                    {
                        DataGridComboBoxColumn column = new DataGridComboBoxColumn();
                        column.Header = field.name;
                        column.ItemsSource = field.group;
                        column.SelectedValueBinding = new Binding(field.name)
                        {

                        };
                        dgwDataMain.Columns.Add(column);
                    }
                    else
                    {
                        DataGridTextColumn column = new DataGridTextColumn();
                        column.Header = field.name;
                        column.Binding = new Binding(field.name)
                        {
                            Mode = BindingMode.TwoWay,
                            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                            NotifyOnSourceUpdated = true,
                            NotifyOnTargetUpdated = true
                        };
                        dgwDataMain.Columns.Add(column);
                    }
                }
ice 13
  • 333
  • 4
  • 17

1 Answers1

0

Solution for WinForm DataGridView:

In your code where you creating a ComboBox columns add next row:

column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter 
Fabio
  • 31,528
  • 4
  • 33
  • 72
  • DataGridTextColumn has no definition for DefaultCellStyle. – ice 13 Mar 15 '13 at 12:17
  • @Ice 13 I was wonder too, when seen a "WPF" tag. On my information WPF doesn't have a DataGridView. – Fabio Mar 15 '13 at 12:23
  • it has System.Windows.Controls.DataGrid – ice 13 Mar 15 '13 at 12:34
  • I am not familiar with WPF, but only I know you need workaround with – Fabio Mar 15 '13 at 12:46
  • Sorry, my bad. Thank you for the tip. – ice 13 Mar 15 '13 at 13:37
  • @Ice 13, if you will get a working solution for this question, please add own answer here, just for next users... – Fabio Mar 15 '13 at 15:24
  • @Ice 13, check this: http://stackoverflow.com/questions/3652318/datagrid-text-alignment. There some example of creating own style for DataGridCell, if it can be used in your DataGridComboBox... – Fabio Mar 15 '13 at 15:34
  • I have to disable AutoGenerateColumns and it only works for TextBoxColumns (not for ComboBoxColumns). – ice 13 Mar 15 '13 at 15:59