How to Bind Datatable to Datagrid

how to bind datatable to datagridview in c#

Try this:

    ServersTable.Columns.Clear();
ServersTable.DataSource = SBind;

If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:

for (int i = 0; i < ServersTable.ColumnCount; ++i) {
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}

Binding DataTable to DataGrid. WPF MVVM

The problem is most probably related to the DataTable initialization, DataGrid will auto-generate columns when a new ItemsSource is set, but it will not re-generate columns when columns are added to the underlying table after initialization.

Solution 1:

Create all columns on initialization of the DataTable, before binding it to the DataGrid.

Solution 2:

Force refresh the ItemsSource. It should work like this, but I highly recommend Solution 1 if possible:

var tempTable = oTable;
oTable = null;
RaisePropertyChanged("oTable");
oTable = tempTable;
RaisePropertyChanged("oTable");

How to Bind DataTable to DataGridView

You just created a blank DataTable and then you are trying to add data to particular columns like Id, Model and Status.

You have to add those columns as well.

DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Model");
table.Columns.Add("Status", typeof(string)); //with type

There is no issue in biding.

Also you can project your required column to an Anonymous type and then bind that to your data grid like:

var result = ctx.ConsumerProducts
.Select(r=> new
{
Id = r.ID,
Model = r.Model,
Status = "Offline"
}).ToList();
dataGridView1.DataSource = result;

DataTable as DataGrid.ItemsSource

Assuming you're in WPF simply say:

DGrid.ItemsSource = dt.AsDataView();

No need to manually setup your columns on your DataGrid, assigning the DataTable will set these up for you.

Binding a DataTable to DataGrid WPF (VB.net)

You can simply add column in DataTable like below:

 With dt.Columns
.Add("SrNo", GetType(Integer))
.Add("Name", GetType(String))
End With

And in XAML add
ItemsSource="{Binding}"

Now before adding row to datatable add below line:

    dg.ItemSource= dt.DefaultView()

Now add rows to datatable and it will reflect to your datagrid automatically.



Related Topics



Leave a reply



Submit