D. Caan
D. Caan

Reputation: 2019

Show values of a DataTable

I have a DataTable being created:

DataTable datatable = new DataTable();

After populating the DataTable with some data, I'm trying to show its data in a DataGrid:

dataGrid1.DataContext = datatable.DefaultView;

My DataGrid has this configuration:

<DataGrid AutoGenerateColumns="False" Height="124" HorizontalAlignment="Left"
          Margin="41,92,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="335" 
          DataContext="{Binding}" ColumnHeaderHeight="20" RowHeight="20" />

Although my DataTable has the expected data in it, the DataGrid is empty.

I'm sure there's something wrong with my code, but I can't find what. How can I correctly show data in the DataGrid using data from a DataTable in WPF?

Upvotes: 1

Views: 175

Answers (2)

Siva G
Siva G

Reputation: 98

DataTable table = new DataTable();
DataColumn column;
DataRow row;
DataView view;
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "name";
table.Columns.Add(column);

// Create new DataRow objects and add to DataTable.    
for (int i = 0; i < 5; i++)
{
    row = table.NewRow();
    row["id"] = i;
    row["name"] = "Name " + i.ToString();
    table.Rows.Add(row);
}

dataGrid1.ItemsSource = table.DefaultView;

Remove AutoGenerateColumns="False" Or Set AutoGenerateColumns="True"

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39956

When you use AutoGenerateColumns="False" in your DataGrid you should also use <DataGrid.Columns> to get full control of which columns are shown and how their data should be viewed and edited. Or set the AutoGenerateColumns to True so that the DataGrid will automatically generate appropriate columns for you:

AutoGenerateColumns="True"

Also you should set your DataGrid's ItemsSource instead of DataContext:

dataGrid1.ItemsSource = datatable.DefaultView;

Upvotes: 3

Related Questions