i work on C# vs05 ...
DataTable dt=CreateTable(_oGeneralReports);//collection _oGeneralReports
i want a method that Converting a Collection into a DataTable ..dt contain the collection value.....help me to get this
You'll have to make a new data table and manually add all the columns to it, then loop through the collection adding each item to the table. e.g
public DataTable CreateTable(ICollection items)
{
DataTable table = new DataTable();
table.Columns.Add("Column1", typeof(int));
table.Columns.Add("Column2", typeof(string));
foreach (Item item in items)
{
DataRow row = table.NewRow();
row["Column1"] = item.Column1;
row["Column2"] = item.Column2;
table.Rows.Add(row);
}
return table;
}
Related
Here and Two Variable Store Two tables Data Now I want to Add these tables in to DataTable through Foreach Loop ?
var meterData = MeterTable(startDateTime, endDateTime);
var levelData = LevelTable(startDateTime, endDateTime);
var dataTable = new DataTable();
dataTable.Columns.Add("Meter", typeof(string));
dataTable.Columns.Add("Volume", typeof(int));
dataTable.Columns.Add("OpeningBalance", typeof(int));
dataTable.Columns.Add("IN", typeof(int));
dataTable.Columns.Add("Transfer", typeof(int));
dataTable.Columns.Add("OUT", typeof(int));
dataTable.Columns.Add("ClosingBalance", typeof(int));
// how Onward i have not any idea ?
If you want all columns from each table you can do this:
var newTable = new DataTable();
//Copy the meter table into your new table
newTable = meterData.Copy();
//Use .Merge to merge in the level table
newTable.Merge(levelData);
If you want to add new rows, you create a datarow and add it to the datatable:
// Create new DataRow objects and add to DataTable.
for(int i = 0; i < someNumberOfRows; i++)
{
row = newTable.NewRow();
row["column1"] = i;
row["column2"] = "item " + i.ToString();
newTable.Rows.Add(row);
}
If you need to use foreach, I'm assuming you want to iterate the rows in your 2 tables:
foreach(DataRow r in meterData.Rows)
{
row = newTable.NewRow();
row["someColumn"] = r["someColumn"];
row["someOtherColumn"] = r["someOtherColumn"];
newTable.Rows.Add(row);
}
you can add new row through foreach loop like this
var dataTable = new DataTable();
dataTable.Columns.Add("Meter", typeof(string));
dataTable.Columns.Add("Volume", typeof(int));
foreach (var items in Source) //source is the where you want to loop
{
DataRow row = dataTable.NewRow();
row["Meter"] = "meter";
//you can access value of source items through item.NameofTargetField like items.meter
row["Volume"] = 11;
dataTable.Rows.Add(row);
}
Here i am trying to bind the user list uow.Repository<User>().GetAll().ToList(); to DataTable dt but there is a error saying cannot convert type 'system.collections.generic.list ' to 'system.data.datatable' in line dt = uow.Repository<User>().GetAll().ToList();.
Below is my code
public DataTable GetAllUser1()
{
DataTable dt = new DataTable();
dt = uow.Repository<User>().GetAll().ToList();
return dt;
}
Any Help will be highy appreciated.Thank you
Without much code and mess use Linq to data set:
IEnumerable<DataRow> query = uow.Repository<User>().GetAll().AsEnumerable();
DataTable dt = query.CopyToDataTable<DataRow>();
The CopyToDataTable method uses the following process to create a
DataTable from a query:
1.The CopyToDataTable method clones a DataTable from the source table (a DataTable object that implements the IQueryable interface). The
IEnumerable source has generally originated from a LINQ to DataSet
expression or method query.
2.The schema of the cloned DataTable is built from the columns of the first enumerated DataRow object in the source table and the name of
the cloned table is the name of the source table with the word "query"
appended to it.
3.For each row in the source table, the content of the row is copied into a new DataRow object, which is then inserted into the cloned
table. The RowState and RowError properties are preserved across the
copy operation. An ArgumentException is thrown if the DataRow objects
in the source are from different tables.
4.The cloned DataTable is returned after all DataRow objects in the input queryable table have been copied. If the source sequence does
not contain any DataRow objects, the method returns an empty
DataTable.
You can use following method to convert List to DataTable
public DataTable GetAllUser1()
{
DataTable dt = new DataTable();
dt = ToDataTable(uow.Repository<User>().GetAll().ToList());
return dt;
}
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
You can use the following method to convert list to DataTable
public DataTable GetAllUser1()
{
DataTable dt = new DataTable();
dt =ToDataTable(uow.Repository<User>().GetAll().ToList());
return dt;
}
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
DataTable dt = new DataTable();
dt = uow.Repository<User>().GetAll().ToList();
It doesn't work like that. You should use the DataTable methods to fill it. Providing an example would provide better understanding. For example; the User class contains these properties;
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
You should specify the columns for DataTable;
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
Now, you can add rows in a simple loop;
var userList = uow.Repository<User>().GetAll().ToList();
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
foreach (var user in userList)
{
var newRow = dt.NewRow();
newRow["Id"] = user.Id;
newRow["Name"] = user.Name;
dt.Rows.Add(newRow);
}
Also, you can provide a solution dynamically by getting the properties and accessing them using Reflection.
You can not directly convert list to Data Table
instead you can build up a generic function. mentioned in below code. You need to convert your list to build up Data Table Rows and Columns.
public DataTable ConvertTODataTable<T>(IList<T> data)// T is any generic type
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
public DataTable LoadPaymentsList()
{
List< DataTable > lstDts = new List< DataTable >();
// Copy into dt
Datatable dt=new Datatable();
return dt;
}
I don't think there's a better way than simple Row- and Column-Adding:
DataTable mergedTable = new DataTable();
List<DataTable> tableCollection = new List<DataTable>();
/*---------------------------------*/
bool columnsAdded = false;
foreach (DataTable table in tableCollection)
{
if (!columnsAdded)
{
foreach (DataColumn column in table.Columns)
{
mergedTable.Columns.Add(column);
}
columnsAdded = true;
}
foreach (DataRow row in table.Rows)
{
mergedTable.Rows.Add(row);
}
}
You want to have a look into merging tables . Check this for further info on dataTable Merging, http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/
//merging first data table into second data table
dt2.Merge(dt);
dt2.AcceptChanges();
I am trying to determine if i have the first table out of a dataset, however the problem i having by using this
if(ds.Tables[0].TableName == "tablename")
is that the dataset is dynamically built depending on the results from the database, for example an AC unit will have Fan Speed table however a boiler unit will not that will have a Temp table.
Currently i have
DataSet ds = new DataSet("AllUsageEquipment");
foreach (var chanID in allChanIDs)
{
DataTable dt = api.GetTotalEquipmentForAreaLevel(startDate, endDate, period, utility, AreaLevel, AreaLevelID, unitType, chanID);
dt.TableName = dt.Rows[0]["Quantity"].ToString();
ds.Tables.Add(dt);
}
DataTable dtExport = new DataTable();
dtExport.Columns.Add("DateStamp", typeof(string));
foreach (DataTable dt in ds.Tables)
{
dtExport.Columns.Add(dt.Rows[0]["Quantity"].ToString(), typeof(int));
foreach (DataRow dr in dt.Rows)
{
if(//code to determine first datatable)
}
}
As you can see the data set is made up dynamically, using the Quantity returned from the database ('Fan Speed' example)
So i am struggling to get the first table in the dataset.
I am trying to do a foreach loop that stores each row from datatable1 into datatable2, so foreach row in datatable1 store the row in datatable2, this is what I have so far:
public static DataTable datatable2 = new DataTable();
public void createDatatable()
{
profile p = new profile();
DataTable datatable1 = p.getResults(System.Convert.ToInt32(HttpContext.Current.Session["ID"]));
foreach (DataRow dr in datatable1.Rows)
{
datatable2 = datatable1.Copy();
}
}
This just copies the columns too which I don't want, I just want each row stored from datatable2 into datatable1
I assume dataTable1 & dataTable2 has same schema (same number of columns with similar datatype). Don't use .Copy(). Use Rows.Add to copy content as follows,
foreach (DataRow dr in dataTable1.Rows) {
dataTable2.Rows.Add(dr.ItemArray);
}