how to bind datatable to datagridview in c#
Solution 1:
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;
}
Solution 2:
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
Solution 3:
On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.
Solution 4:
// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.
BindingSource SBind = new BindingSource();
SBind.DataSource = dtSourceData;
ADGView1.AutoGenerateColumns = true; //must be "true" here
ADGView1.Columns.Clear();
ADGView1.DataSource = SBind;
//set DGV's column names and headings from the Datatable properties
for (int i = 0; i < ADGView1.Columns.Count; i++)
{
ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
}
ADGView1.Enabled = true;
ADGView1.Refresh();