Thursday, February 21, 2008

Placing ComboBox in Windows Forms DataGrid Cell

A common task found in invoicing application is placing a combobox in a particular colum of a DataGrid. Let's see how to do that in VB.Net.

Imports System.Data.SqlClient

Public Class Form1
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim dr As SqlDataReader
Dim ds As New DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn = New SqlConnection("integrated security=sspi;initial catalog=Northwind")
da = New SqlDataAdapter("select ProductName,CategoryId,UnitPrice from Products", cn)
da.Fill(ds, "Prod")
DataGrid1.SetDataBinding(ds, "Prod")
DataGrid1_CurrentCellChanged(DataGrid1, e)
End Sub

Private Sub Fillcombo()
cmd = New SqlCommand("select * from categories", cn)
dr = cmd.ExecuteReader()
While dr.Read()
End While
End Sub

Private Sub DataGrid1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGrid1.CurrentCellChanged
Dim x, y, h, w As Integer
Dim rect As Rectangle
rect = DataGrid1.GetCurrentCellBounds
x = rect.X + DataGrid1.Left
y = rect.Y + DataGrid1.Top
w = rect.Width
h = rect.Height
ComboBox1.SetBounds(x, y, w, h)
ComboBox1.Visible = True
End Sub
End Class

No comments:

Post a Comment