Though WPF is a Wonderful technology, at times programmers get frustrated with the lack of certain controls. One such control is the DataGrid or GridView. Silverlight 2 infact has a DataGrid, hope in the next release of WPF it will be as feature rich as Windows Forms.
It is very much possible to use Windows Forms controls in WPF.
Start out by dragging a WindowsFormsHost into WPF Windows.
Create an object of System.Windows.Forms..DataGrid and set the Child Property of WindowsFormsHost to the newly created DataGrid object. WindowsFormsHost can have only one child as is obvious form the Child Property.
System.Windows.Forms.DataGrid dg = new System.Windows.Forms.DataGrid();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
windowsFormsHost1.Child = dg;
}
Now you can work with the DataGrid just like you work with it in Windows Forms.
Here is the complete code for connecting the DataGrid to a DataSet.
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
System.Windows.Forms.DataGrid dg = new System.Windows.Forms.DataGrid();
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
windowsFormsHost1.Child = dg;
cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data source=.\sqlexpress");
cnn.Open();
da = new SqlDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
dg.DataSource = ds.Tables["Cat"];
}
Thursday, August 14, 2008
Wpf and Windows Forms Controls Interop
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")
cn.Open()
da = New SqlDataAdapter("select ProductName,CategoryId,UnitPrice from Products", cn)
da.Fill(ds, "Prod")
DataGrid1.SetDataBinding(ds, "Prod")
Fillcombo()
DataGrid1_CurrentCellChanged(DataGrid1, e)
End Sub
Private Sub Fillcombo()
cmd = New SqlCommand("select * from categories", cn)
dr = cmd.ExecuteReader()
While dr.Read()
ComboBox1.Items.Add(dr("CategoryName"))
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