In my previous blog, I talked about a new WindowsForms Control “ElementHost” to host WPF controls inside a WindowsForms Project. On the contrary, “WindowsFormsHost” is used to host winforms controls inside a WPF application. WindowsFormsHost is a very important control to get the rich capabilities of WinForms world into WPF. WPF does not have a story yet for some of the controls like DataGridView, ToolStrips etc which have lots of uses.
In this blog, I will concentrate on getting a DataGridView getting displayed inside a WPF application. I will make use of databinding to get data from the Customers Table of the SaveNorthWind Database.
The steps would be as follows
BindingSource dataBindingPrep()
{
SaveNorthwindDataSet dataset = new SaveNorthwindDataSet();
dataset.DataSetName = "SaveNorthwindDataSet";
dataset.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
SaveNorthwindDataSetTableAdapters.CustomersTableAdapter tableadapter = new WpfApplication1.SaveNorthwindDataSetTableAdapters.CustomersTableAdapter();
BindingSource bs = new BindingSource();
bs.DataMember = "Customers";
bs.DataSource = dataset;
tableadapter.ClearBeforeFill = true;
// filling the table
tableadapter.Fill(dataset.Customers);
return bs;
}
public Window1()
InitializeComponent();
//adding the datagridview
DataGridView dgv = new DataGridView();
dgv.DataSource = dataBindingPrep();
//setting the child property
windowsFormsHost1.Child = dgv;
//hooking events to DGV
dgv.CellContentClick += new DataGridViewCellEventHandler(dgv_CellContentClick);
when you run your app, you can see the wpf window showing the data from the customers table in a datagridview.
You can also try to add events to the datagridview. In my example, I choose to show a messagebox when I click on the column1 of the DGV. I can do this by implementing the cellcontentclick event as follows.
void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
DataGridView dgv = (DataGridView)sender;
if (e.ColumnIndex == 0)
System.Windows.MessageBox.Show("Clicked on " + dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);