Home > DeveloperSection > Articles > WindowsFormsHost control in WPF

WindowsFormsHost control in WPF


WPF WPF 
Ratings:
0 Comment(s)
 21387  View(s)
Rate this:

WindowsFormsHost control in WPF

In XAML we can use <WindowsFormHost /> element to use WindowsFormsHost control in WPF. We know that WPF provide a great user interface, but still a very younger framework and sometime it doesn’t provide everything what we want. For example there is number of controls in Windows Forms that doesn’t exist in WPF such as DataGridView control or BindingNavigator control. So for using these controls on WPF platform we need WindowsFormsHost control. In this demonstration I will show you how to use DataGridView control in WindowsFormsHost control.

Steps to implementing WindowsFormsHost control in WPF

<![if !supportLists]> Ø  <![endif]> Add references of System.Windows.Forms and WindowsFormIntegration by using add Reference dialog box.

<![if !supportLists]> Ø  <![endif]> Add following schema in XAML file

xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

 A XAML code which represents use WindowsFormsHost control in WPF

<Grid>

        <Grid.RowDefinitions>

            <RowDefinition />

            <RowDefinition Height="40" />

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition />

        </Grid.ColumnDefinitions>

        <WindowsFormsHost Grid.Row="0" Grid.Column="0">

            <WinForms:DataGridView x:Name="dataGridView1">   

            </WinForms:DataGridView>

        </WindowsFormsHost>

        <Button x:Name="button1" Content="Get Data" Grid.Row="1" Grid.Column="0" Click="button1_Click" />

</Grid>

 

Code for retrieving data in Data Grid View control

private void button1_Click(object sender, RoutedEventArgs e)

{

            SqlConnection con = new SqlConnection();

            con.ConnectionString = "Data Source=UTTAM-PC3\\MindStick;User Id=sa;Password=mindstick;Initial Catalog=Workbook";

            con.Open();

            string query = "select * from Student";

            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataReader dr = cmd.ExecuteReader();

            DataTable dt = new DataTable();

            dt.Load(dr);

            dataGridView1.DataSource = dt.DefaultView;

            con.Close();

}

 

Output of the following code snippet is as follows

WindowsFormsHost control in WPF

WindowsFormsHost control in WPF

 


Don't want to miss updates? Please click the below button!

Follow MindStick