This article will show you how you can transfer datatable row
values to class list collection using C#.Net. In this first i have prepared the date to datatable and after that i have transferred data to datatable using C#.Net.
Some of my previous articles are as follows: Browse,
Read and Populate or Show or Bind CSV File Data In GridView Using C#.Net in
Asp.net, Gridview
Auto Generate Row Number In Asp.Net Using C#.Net, How
To Read XML File In DataSet And Display in DataGridview Using C#.Net, Get
Distinct Value From DataTable Using C#.Net and VB.Net, Read
XML File Data Using Linq Query and Add in DataTable to Bind GridView in Asp.net
Using C#.Net, Bind
& Search XML File Data and Display in GridView in Asp.net Using C#.Net, Bind
Asp.net DropdownList Control by XML File Data Using DataSet in C#.Net, Bind
Asp.net ListBox Control by XML File Data Using DataSet in C#.Net, Line
Chart in Asp.Net Using C#.Net and VB.Net.
public DataTable DataTableValue()
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Id");
dt.Columns.Add("CountryName");
dt.Columns.Add("Population");
dt.Columns.Add("Code");
DataRow dataRow1 =
dt.NewRow();
dataRow1["Id"] = 1;
dataRow1["CountryName"] = "India";
dataRow1["Population"] = "125
Cr";
dataRow1["Code"] = "IN";
dt.Rows.Add(dataRow1);
DataRow dataRow2 =
dt.NewRow();
dataRow2["Id"] = 2;
dataRow2["CountryName"] = "Pakistan";
dataRow2["Population"] = "50
Cr";
dataRow2["Code"] = "PK";
dt.Rows.Add(dataRow2);
DataRow dataRow3 =
dt.NewRow();
dataRow3["Id"] = 3;
dataRow3["CountryName"] = "United
States";
dataRow3["Population"] = "25
Cr";
dataRow3["Code"] = "US";
dt.Rows.Add(dataRow3);
return dt;
}
|
You can
fill your datatable with your sql database table value also. After this we will
create a class file and add the below code into the class.
public class CountryDetail
{
public int Id { get; set; }
public string CountryName { get; set; }
public string Population { get; set; }
public string Code { get; set; }
}
|
After this
I will show you the way to transfer the datatable value to the list collection.
Now check the below code.
DataTable dt = new DataTable();
dt =
DataTableValue();
//Class list object
List<CountryDetail>
countryDetail = new List<CountryDetail>();
for (int i = 0; i <
dt.Rows.Count; i++)
{
countryDetail.Add(new CountryDetail
{
Id = Convert.ToInt32(dt.Rows[i]["Id"]),
CountryName = dt.Rows[i]["CountryName"].ToString(),
Code = dt.Rows[i]["Code"].ToString(),
Population = dt.Rows[i]["Population"].ToString()
});
}
|
In above
code I have shown you to first read the datatable and after that add the value
into the list collection. Check the final output in debug mode. Have a look the
below output.
0 comments:
Please let me know your view