How to Bind Datatable to Datagridview in C#

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;
}

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;

Bind DataTable to Datagridview that already have column defined

DataGridView columns have property named DataPropertyName just set them to your DataTable column names and you are set.

foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.Name);
col.DataPropertyName = col.Name;
}

this should work.

C# Bind DataTable to Existing DataGridView Column Definitions

You need to ensure each column's DataPropertyName property is set to the corresponding name of the DataColumn's ColumnName.

You may also need to set the DataGridView's AutoGenerateColumns property to false.

I found the solution here.

C# - Datagridview cannot bind data from datatable

It looks like columns are added in the designer and your DataGridView's AutoGenerateColumns is set to false.
As your columns count doesn't match your data source, therefore you are getting this error.

To fix this, either

  1. Add columns in the designer to match the Data source
  2. or, set dataGridView1.AutoGenerateColumns to True

See reference here: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns(v=vs.110).aspx



Related Topics



Leave a reply



Submit