I have some Data returning from a Context. Data has being pulled by spCmsCategoriesReadHierarchy
.
I need take all Data from Context and populate my DataSet. My final goal is to populate a TreeView Control with DataSet object.
Any ideas? Thanks for your time and patience.
using (TestHierarchyEntities context = new TestHierarchyEntities())
{
int n = 0;
Int16 sl = 1;
ObjectParameter nn = new ObjectParameter("nn", typeof(int));
// Create a Data Set where adding the result of context
DataSet dataSet = new DataSet("myDataSet");
foreach (CmsCategory categories in context.spCmsCategoriesReadHierarchy(n,sl,nn))
{
}
}
Sure, you can manually copy the data over from the object to a data row within the dataset.
DataSet dataSet = new DataSet("myDataSet");
dataSet.Tables.Add(new DataTable());
//Setup the table columns.
foreach (CmsCategory categories in context.spCmsCategoriesReadHierarchy(n,sl,nn))
{
DataRow row = dataSet.Tables[0].NewRow();
row["A"] = categories.A;
row["B"] = categories.B;
dataSet.Tables[0].Rows.Add(row);
}
If you are not looking to explicitly copy over the properties to the data row, you can also use reflection to do the copying.
This method will convert a list of objects to a datatable. It was given as an answer to this question.
/// <summary>
/// Create data table from list.
/// https://stackoverflow.com/questions/18746064/using-reflection-to-create-a-datatable-from-a-class
/// </summary>
public static DataTable CreateDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}