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
C# Sending Mails with Images Inline Using Smtpclient
Why We Need Thread.Memorybarrier()
Icecast 2: Protocol Description, Streaming to It Using C#
Recursive Hierarchy - Recursive Query Using Linq
How to Export a Jqgrid Data to Excel Using C#
How to Get Current Page Url in MVC 3
Posting JSON Data to ASP.NET MVC
HTML Agility Pack Strip Tags Not in Whitelist
Error in Process.Start() -- the System Cannot Find the File Specified
How to Copy Part of an Array to Another Array in C#
Windows.Forms.Timer or System.Threading.Timer
Why Is Array.Length an Int, and Not an Uint
Retrieve Image from Database in ASP.NET
How to View Msil/Cil Generated by C# Compiler? Why Is It Called Assembly