Wednesday, May 9, 2012

Convert a Generic List into a Datatable in asp.net

According to my application requirement ,i need to bind the data to data table from List in asp.net using C#.net.For this i just create table dynamically then bind the data using loop iteration on list.
In the below we can see two methods which are CreateDataTable which is used to create a data table and AddDataToTable which is used to bind the data .
public DataTable converttoTable(List<string> list, string tableName)
{
DataTable table;
table = CreateDataTable(); 
if (list.Count > 0)
{
foreach (string item in list)
{
AddDataToTable(item, table);
}
}
return table;
}
This function will execute when the items are added to data table.
private void AddDataToTable(string rowItem, DataTable myTable)
{
try
{
DataRow row;
row = myTable.NewRow();
string[] itemStringArray = SplitByString(rowItem, "[]");
row["Iame"] = itemStringArray[0];
row["Id"] = itemStringArray[1];
row["Address"] = itemStringArray[2] == "" ? "0" : itemStringArray[2];
row["Year"] = itemStringArray[3];
row["salary"] = itemStringArray[4];
myTable.Rows.Add(row);
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
//create a table dynamically
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Name";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Id";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Address";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Year";
myDataTable.Columns.Add(myDataColumn);           

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Salary";
myDataTable.Columns.Add(myDataColumn);

return myDataTable;
}

No comments:

Bel