C#: WinForms – How to use DataTable as DataGridView datasource and DataTable column with HeaderText property
I did something like that today so I thought to share. Example of use DataTable with DataGridView control. In addition HeaderText property of DataGridView is assigned based on DataTable DataColumn.Caption property value.
using System.Data;
using System;
private DataTable myDataTable = new DataTable();
DataColumn getNewColumn(string columnName, string columnCaption
, string columnType)
{
// Create a new column to be used in the DataTable
DataColumn dc =
new DataColumn(columnName, System.Type.GetType(columnType));
// Column caption can be used later for HeaderText prop
// in DataGridView
dc.Caption = columnCaption;
return dc;
}
void CreateNewRow(string[] rowData)
{
// Create a DataRow based on the DataTable
DataRow dr = myDataTable.NewRow();
// Add values to the DataRow columns
int i = 0;
foreach (string fieldData in rowData)
{
if (i < dataTable.Columns.Count)
// assign by index
dr[i] = fieldData;
else
break;
i++;
}
// Add the row to the DataTable
myDataTable.Rows.Add(dr);
}
private void FillDataGridViewFromTextFile(string filename)
{
// Clear last results from DataGridView
if (DataGridView1.RowCount > 0)
myDataTable.Rows.Clear();
if (myDataTable.Columns.Count == 0)
{ // if DataTable is not constructed than Add Columns
// to the datatable
myDataTable.Columns.Add(getNewColumn("ComputerName"
, "Computer name"
, "System.String"));
}
// Load data from text file into DataTable
using (System.IO.StreamReader reader
= new System.IO.StreamReader(filename))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
if (!String.IsNullOrEmpty(line))
{
// add row data to "columns array"
string[] rowData = new string[] { line };
// add new row to DataTable
CreateNewRow(rowData);
}
}
}
// Assign DataTable to DataGridView
DataGridView1.DataSource = myDataTable;
// Copy DataTable columns Caption property
// to DataGridView HeaderText property
foreach (DataColumn dc in myDataTable.Columns)
{
DataGridView1.Columns[dc.ColumnName].HeaderText = dc.Caption;
}
}
P.S. To get all the data OUT of the gridview and back INTO a datatable
DateTable tbl = Gridview1.DataSource as DataTable;

(2,925)

