Row headers in data format - for display in datagridview format

In any case, in order to store row header information in datatable so that when I bind it to datagridview, does it automatically display column and row headers in C #?

+5
source share
2 answers

LINQPad Demo -Program

As I understand it, you would like to add the column name as values ​​in the datatable / datagridview. The following is the LINQPad -Program, which you can easily copy to Linqpad for playback. The code adds the column names to the first row in the data table. You can easily associate this dataset with a grid view, but keep in mind that each column of the data table must be of type string.

void Main()
{
    GetDataTable().Dump();
}

public DataTable GetDataTable()
{
    var dt = new DataTable();   
    dt.Columns.Add("Id", typeof(string)); // dt.Columns.Add("Id", typeof(int));
    dt.Columns["Id"].Caption ="my id";  
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Job", typeof(string));
    dt.Rows.Add(GetHeaders(dt));
    dt.Rows.Add(1, "Janeway", "Captain");
    dt.Rows.Add(2, "Seven Of Nine", "nobody knows");
    dt.Rows.Add(3, "Doctor", "Medical Officer");
    return dt;
}

public DataRow GetHeaders(DataTable dt)
{
    DataRow dataRow = dt.NewRow();      
    string[] columnNames = dt.Columns.Cast<DataColumn>()
                                 .Select(x => x.ColumnName)
                                 .ToArray();    
    columnNames.Dump();
    dataRow.ItemArray = columnNames;
    return dataRow;
}

Result of Linqpad programm

Update 2019-06 with additional explanation and alternative code

The method GetHeadersis not the easiest option to get headers. Previously, the extension method was Cast<TResult>(IEnumerable)used in the DataColumnCollection-Class . An alternative would be to simply iterate over the collection - this is what is done in GetHeadersNewT

public DataRow GetHeadersNew(DataTable dt)
{
    DataRow row = dt.NewRow();      
    DataColumnCollection columns = dt.Columns;
    for (int i = 0 ;i <columns.Count ;i++)
    {
         row[i] = columns[i].ColumnName;
    }       
    return row;
}

, , , .

+4

, , #. datatable foreach. , :

DataTable dt = new DataTable();
// code here to get your datatable
dt.Columns.Add("rowheader");
foreach (DataRow r in dt.Rows)
{
    r["rowheader"] = "my nice row header";
}

.

SQL- "extra" . :

Select *, 'my nice row header' as rowheader from myTable

SQL .

+3

All Articles