简体   繁体   中英

DataTable columns in C#

I currently have this code, I'm aware how to print out the rows, but I can't figure out how to get my column headers? I don't want to use the solution I had that I commented out because I want to make the code generic so that I can use it for other lists too.

static DataTable ConvertListToDataTable(List<List<string>> list)
{
    // New table.
    DataTable table = new DataTable();

    /* table.Columns.Add("Employee ID");
       table.Columns.Add("First Name");
       table.Columns.Add("Last Name");
       table.Columns.Add("Job Title");
       table.Columns.Add("Address");
       table.Columns.Add("City"); 
    */

    foreach(List<string> row in list) {
        table.Rows.Add(row.ToArray());
    }

    return table;
}

It's impossible to derive the column headers from the List<List<string>> since the information is simply not available. You could provide them per parameter:

static DataTable ConvertListToDataTable(List<List<string>> list, IList<string> columnNames)
{
    DataTable table = new DataTable();
    foreach (string columnName in columnNames)
        table.Columns.Add(columnName);
    foreach (List<string> row in list)
    {
        if (row.Count != columnNames.Count)
            throw new ArgumentException(string.Format("Invalid data in list, must have the same columns as the columnNames-argument. Line was: '{0}'", string.Join(",", row)), "list");
        DataRow r =  table.Rows.Add();
        for (int i = 0; i < columnNames.Count; i++)
            r[i] = row[i];
    }
    return table;
}

How to use:

string[] columns = { "Employee ID", "First Name", "Last Name", "Job Title", "Address", "City"};
DataTable tblEmployee = ConvertListToDataTable(employees, columns);

But instead of using a List<List<string>> (or a DataTable ) to store your employees you should use a custom class, for example Employee with all those properties. Then you can fill a List<Employee> . On that way your code is much better to read and to maintain.

The following code gives you the facility to convert an IEnumerable type to DataTable with dynamic Headers using System.Reflection.PropertyInfo. try to use this.

    public static DataTable EnumerableToDataTable<T>(IEnumerable<T> varlist)
    {
        DataTable dtReturn = new DataTable();

        // column names  
        PropertyInfo[] oProps = null;

        if (varlist == null) return dtReturn;

        foreach (T rec in varlist)
        {
            // Use reflection to get property names, to create table, Only first time, others will follow  
            if (oProps == null)
            {
                oProps = ((Type)rec.GetType()).GetProperties();
                foreach (PropertyInfo pi in oProps)
                {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }

                    dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                }
            }

            DataRow dr = dtReturn.NewRow();

            foreach (PropertyInfo pi in oProps)
            {
                dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                (rec, null);
            }

            dtReturn.Rows.Add(dr);
        }
        return dtReturn;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM