How to Bind DataGrid using DataTable from Database in WPF C#

Leave a Comment
IN this tutorial, we have to learn how to bind datagrid using DataTable from Database in WPF Application in C# and VB.Net

To Bind DataGrid, I have created Database called Student and add one table called Student as shown below -
DataGrid using DataTable from Database


Now, add DataGrid to your WPF Form MainWindows.xaml as shown below-

<Window x:Class="WPFDataGridDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid AutoGenerateColumns="False" Name="dataGrid1" ItemsSource="{Binding Path=.}" AlternatingRowBackground="Green">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding name}" />
                <DataGridTextColumn Header="City" Binding="{Binding city}" />
                <DataGridCheckBoxColumn Header="City" Binding="{Binding active}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


To Bind the DataGrid add below code to your MainWindows.xaml.cs file as shown below -
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
namespace WPFDataGridDemo
{
    public partial class MainWindow : Window
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString);
     
        public MainWindow()
        {
            InitializeComponent();
            con.Open();
            SqlCommand com = new SqlCommand("Select * FROM Student");
            com.Connection = con;
            com.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            SqlDataAdapter sdt = new SqlDataAdapter(com);
            sdt.Fill(dt);
            dataGrid1.DataContext = dt;
            con.Close();
        }
    }
}

Demo
How to Bind DataGrid using DataTable from Database in WPF C# and VB.Net


0 comments:

Post a Comment