Posts Tagged ‘LIST’
Convert ILIST, LIST to DataSet with child tables and relations
There was requirement to convert ILIST or LIST to DataSet so that it can be assigned to some of the controls like Grid or DevExpress Grid. For that i have written following class to convert from LIST or ILIST to DataSet
- Converts only ILIST and LIST
- Convert sub lists to another table which will be related to the parent list
- Creates Relation between tables
- Works only on the properties not on fields. You can easily modify it for that
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace TowardsNext
{
public static class ListConvertor
{
public static DataSet ConvertToDataSet<T>(IList list)
{
DataSet dataSet = new DataSet();
CreateDataSet(dataSet, typeof(T), false);
FillDataSet(typeof(T), list.ToList(), dataSet, -1);
CreateRelations(dataSet, typeof(T), null);
return dataSet;
}
///
/// Create the structure for all the tables in the data set
///
/// Data set in which tables will be created
/// Type of which dataset has to be created
/// Whether current type is a child table
private static void CreateDataSet(DataSet dataSet, Type type, bool isChildTable)
{
DataTable dataTable = new DataTable(type.Name);
//Create the ID columns for having relation in the tables
dataTable.Columns.Add(new DataColumn("ID", typeof(int)));
if (isChildTable)
{
dataTable.Columns.Add(new DataColumn("ParentID", typeof(int)));
}
// Create the structure for the data tables to be
// added in the the data set
foreach (PropertyInfo pInfo in type.GetProperties())
{
if (pInfo.PropertyType.IsGenericType &&
(pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
// If associate lists are there make then another table
CreateDataSet(dataSet,
pInfo.PropertyType.GetGenericArguments()[0],
true);
}
else
{
dataTable.Columns.Add(new DataColumn(pInfo.Name, pInfo.PropertyType));
}
}
//Add the table to the dataset
dataSet.Tables.Add(dataTable);
}
///
/// Fill all the tables of data set with data in the respective list
///
/// Type of which datatable is to be filled
/// List of data
/// Data Set in which data tables will be filled with data
/// ID of parent record. If -1 one then no parent
private static void FillDataSet(Type type, IList list, DataSet dataSet, int parentID)
{
PropertyInfo[] propertyInfos = type.GetProperties();
DataTable dataTable = dataSet.Tables[type.Name];
int id = dataTable.Rows.Count + 1;
foreach (object item in list)
{
DataRow row = dataTable.NewRow();
// Set new id and related parent id
row["ID"] = id;
if (parentID != -1)
row["ParentID"] = parentID;
// Load all the data from the properties of the type
// and save them into the datatable
foreach (PropertyInfo info in propertyInfos)
{
if (info.PropertyType.IsGenericType &&
(info.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| info.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
IList subList = (IList)info.GetValue(item, null);
if (subList != null && subList.Count > 0)
{
FillDataSet(subList[0].GetType(),
subList,
dataSet, id);
}
}
else
{
row[info.Name] = info.GetValue(item, null);
}
}
dataTable.Rows.Add(row);
id++;
}
}
///
/// Creates the relation between the tables according to the
/// type and parent table on field ID and ParentID
///
/// Data set containing parent and child table
/// Type of the list
/// Parent table to which relations has to be done
private static void CreateRelations(DataSet dataSet, Type type, DataTable parentTable)
{
DataTable dataTable = dataSet.Tables[type.Name];
// If parent table exsits then create relation
// with child table on field Parent ID
if (parentTable != null)
{
dataSet.Relations.Add(
new DataRelation(parentTable.TableName + "_ID_"
+ "PARENTID_" + dataTable.TableName,
parentTable.Columns["ID"],
dataTable.Columns["ParentID"]));
}
// Check for other lists under current object
// go for another relation if exists
foreach (PropertyInfo pInfo in type.GetProperties())
{
if (pInfo.PropertyType.IsGenericType &&
(pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
// If associate lists are there make then another table
CreateRelations(dataSet,
pInfo.PropertyType.GetGenericArguments()[0],
dataTable);
}
}
}
}
}
Tested with following code
;public class Student
{
public string Name { get; set; }
public string Class { get; set; }
}
public class Teacher
{
public string Name { get; set; }
public string Address { get; set; }
public List<Student> Students { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
students.Add(new Student { Name = "Ram Prasad", Class = "LKG" });
students.Add(new Student { Name = "Dina Nath", Class = "Prep" });
List<Teacher> teachers = new List<Teacher>();
teachers.Add(
new Teacher{
Name="Om Prakash",
Address="Mangalore",
Students = students
});
teachers.Add(new Teacher
{
Name = "Om Prakash 2",
Address = "Gurgaon",
Students = students
});
DataSet dataSet = ListConvertor.ConvertToDataSet<Teacher>(teachers);
}
}
It is not tested in all the cases and condition only checked with few cases and requirement. If any problem do reply, i will fix it up and re-post it. After converting we assigned it to devexpress grid and get the following successful output
Listing SQL Server Instances running in network with details C#
To list the server running in the listbox or the grid we can use following code and give user a option to select the server to whom he wants to connect
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
namespace ListSQLServer
{
public partial class serverListing : Form
{
public serverListing()
{
InitializeComponent();
}
private void listButton_Click(object sender, EventArgs e)
{
DataTable dtServer = SqlDataSourceEnumerator.Instance.GetDataSources();
serverDetailsGrid.DataSource = dtServer;
}
}
}
you will get the following result in the grid

