Reputation: 251
Here is my code. XAML :
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding }" Height="200" Name="dataGrid1" Width="200" />
cs :
SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
// MessageBox.Show(cmd.CommandText);
dataGrid1.ItemsSource = dt.DefaultView;
It displays line on grid.Not the actual data.Kindly help. Thanks in advance.
Upvotes: 2
Views: 637
Reputation: 19895
Datatable
will not generate datagrid rows with AutoGenerateColumns="False"
.
Please change it to AutoGenerateColumns="True"
or add your own data columns in <Datagrid.Columns>
property.
Upvotes: 2
Reputation: 5150
If you using ItemSource you have to generate an ItemTemplate. Binding WPF DataGrid to DataTable using TemplateColumns
Using instead DataContext:
SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
// Here:
dataGrid1.DataContext = dt.DefaultView;
DataContext is a general (dependency) property of all descendants of FrameworkElement. Is is inherited through the logical tree from parent to children and can be used as an implicit source for DataBinding. It does not do anything by itself, you must basically databind to it.
ItemsSource is the property identifying the source for templated generation of items in an ItemsControl derived control (or HierarchicalDataTemplate).
Upvotes: 0