ComboBox in DataGrid

B

Brian Tkatch

This is mostly for the fun of it. Just saw it in the FAQ and figured
i'd quickly give it a shot.

The syncfusion FAQ
<URL:http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c44c.aspx#q480q>
mentions:

"5.9 How can I put a combobox in a column of a datagrid?

There are several ways to go about this task. The simplest way involves
adding a single combobox to the DataGrid.Controls, and then selectively
displaying it as needed when a combobox cell becomes the currentcell.
All the work is done in a few event handlers and no overrides or
derived classes are necessary. This technique is discussed in Microsoft
KB article Q323167."

But the KB is missing. So, i decided to play with it.

Open a form, put in a DataGrid, then use the following code:

Dim CBox As New ComboBox

Private Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim Table As New DataTable
Dim Counter As Integer

For Counter = 0 To 9
Table.Columns.Add()
Table.Columns(Counter).DefaultValue = ""
Next

For Counter = 0 To 9
Table.Rows.Add(Table.NewRow)
Next

DataGrid1.DataSource = Table

DataGrid1.Controls.Add(CBox)

For Counter = 0 To 9
CBox.Items.Add(Counter)
Next

Move_CBox()

End Sub

Private Sub DataGrid1_CurrentCellChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles DataGrid1.CurrentCellChanged
Move_CBox()
End Sub

Sub Move_CBox()

Dim Rect As Rectangle = DataGrid1.GetCurrentCellBounds

With CBox
.Hide()
.Left = Rect.Left
.Top = Rect.Top
.Width = Rect.Width
.Height = Rect.Height
.Show()
.BringToFront()
End With

End Sub

Setting the comboboxe's height doesn't seem to actually do anything.
Also, scrolling the Grid leaves the ComboBox where it is, look like the
OnScroll event would need to figure out what's going on.

Hide the ComboBox before moving it, otherwise it shows it in its new
place, then hides the old one, making a moment where two ComboBoxes are
displayed.

BringToFront is required to show it on top of the textbox edit. Using a
CheckBox ColumnStyle would not require this step.

B.
 
S

Samuel Shulman

Ther is a newer version called DataGridView that has this functionality
built in (I use in VS.NET 2005)
 
B

Brian Tkatch

Samuel said:
Ther is a newer version called DataGridView that has this functionality
built in (I use in VS.NET 2005)

The corporate standard here is still 2003. (2005 is being evaluated.)
So, i may be stuck for now. But i'm going to have to check that out.

Thanx.

B.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top