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
- Add columns in the designer to match the Data source
- 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
"Interface Not Implemented" When Returning Derived Type
What Are C# Lambda's Compiled Into? a Stackframe, an Instance of an Anonymous Type, Or
Datagrid Shows Path of Image Instead of Image Itself
Using Razor Outside of MVC in .Net Core
Design Pattern for Handling Multiple Message Types
Rendering Partial Views Using Ajax
Can You Create SQL Views/Stored Procedure Using Entity Framework 4.1 Code First Approach
Multipleactiveresultsets=True or Multiple Connections
Efficient Cartesian Product Algorithm
Convert Am/Pm Time to 24 Hours Format
.Net:How to Get the Type of a Null Object
Is Unityscript/JavaScript Discontinued
How to Use Push Notifications in Xamarin Forms