Fill LINQ data to a data table in C#

Load LINQ data to a variable varlist of data type var. Pass the variable varlist to the below function.


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

//Column names
PropertyInfo[] oProps = null;

if (varlist == null) return dtReturn;

foreach (T rec in varlist)
{
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;
}
Advertisements
Posted in C#, Programming | Tagged , , , | Leave a comment

File path not available for file control in firefox

For some security reasons modern web browsers will return only file name instead of file name with directory path from client computer.

To upload a file to the server from client computer you can use the SaveAs method of file control see below.

string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/"+filename));
Posted in Programming | Tagged , , , , | Leave a comment