views:

417

answers:

2

Problem: My DataGridView has tall cells because of some images in previous columns. So the ComboBox column shows a ComboBox spread on the whole height (and width) of each cell, which just looks unacceptable.

Question: Is there a way to set the size and location of the ComboBox so that it is centered in each cell and maintains its default size?

Note: From googling around it appears that this might be possible by creating my own custom column to host a ComboBox and override the paint event, but before I go that route I want to make sure that's the only way.

+1  A: 

I just recreated your problem, and I have to admit, that sucks! :)

One way to work around is to go into the properties of your ComboBox column, and change the Display Style to Nothing.

This will cause only the selected text to be displayed when then cell is not being editing, the ComboBox will not show up until you edit the cell.

When your row grows higher, you might want to change the DefaultCellStyle so that Alignment is set to Top Left.

If you want the ComboBox shown when the cell is not being edited, take a look at the CellPainting event, it allows you to customize the look of a cell. That might allow you to draw your ComboBox onto your cell.

mlsteeves
+1  A: 

@mlsteeves, thanks for pointing out CellPainting event. I don't know how I managed to overlook it. But here is what I am going with now, seems to provide the result I was looking for:

void DataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == ComboBoxColumnIndex)
    {
     ComboBox comboBox = this.DataGridView.Controls["ColumnComboBox" + e.RowIndex] as ComboBox;
     if (comboBox == null)
     {
      comboBox = this.GetNewComboBox(e.RowIndex);
      comboBox.Name = "ColumnComboBox" + e.RowIndex;
      this.DataGridView.Controls.Add(comboBox);
     }

     if (comboBox != null)
     {
      comboBox.Width = e.CellBounds.Width - 10;
      comboBox.Left = e.CellBounds.Left + ((e.CellBounds.Width - comboBox.Width) / 2);
      comboBox.Top = e.CellBounds.Top + ((e.CellBounds.Height - comboBox.Height) / 2);
     }
    }
}
codelove