This article will show you how you can transfer datatable row values to
class list collection using C#.net and
VB.Net.
Some of my previous articles are as follows: How
To Add Data In Datatable In C#.Net, Transfer
DataTable Row Value to List Collection In C#.Net, Browse,
Read and Populate or Show or Bind CSV File Data In GridView Using C#.Net in
Asp.net, Bind
Class Property to GeidView Using C#.net In Asp.net, Gridview
Auto Generate Row Number In Asp.Net Using C#.Net, How
To Remove Time From DateTime List Using Linq In C#.Net, C#
Dictionary Search Key By Value, C#
Dictionary Get Value By Key, Retrieve
All Files Present inside a Directory & Sub Directory Using C#.Net, Bind
TextBox Control Inside TemplateField Of GridView Using C#.Net In Asp.Net, Enable
and Disable ADO.NET and OLEDB Connection Pooling In .Net.
First prepare 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; }
}
|
So here is the code for the list collection. You can fill your datatable with your sql
database table value also.
public List<CountryDetail>
GetCountryData()
{
List<CountryDetail>
countryDetail = new List<CountryDetail>();
countryDetail.Add(new CountryDetail { Id = 1, CountryName = "India", Code = "IN", Population = "125Cr" });
countryDetail.Add(new CountryDetail { Id = 2, CountryName = "Pakistan", Code = "PK", Population = "50Cr" });
countryDetail.Add(new CountryDetail { Id
= 3, CountryName = "America", Code = "US", Population = "24Cr" });
return countryDetail;
}
|
After this
I will show you the way to transfer the list collection value to datatable. Now
check the below code.
public DataTable
AssignListValueToDataTable(List<CountryDetail> countryDetail)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("CountryName");
dt.Columns.Add("Population");
dt.Columns.Add("Code");
foreach (CountryDetail item in countryDetail)
{
DataRow dataRow =
dt.NewRow();
dataRow["CountryName"] = item.CountryName;
dataRow["Population"] = item.Population;
dataRow["Code"] = item.Code;
dt.Rows.Add(dataRow);
}
return dt;
}
|
In above
code I have shown you to first read the list collection and after that add the
value into the datatable.
Now check
the page load code to activate the transfer code.
protected void Page_Load(object sender, EventArgs e)
{
List<CountryDetail>
countryDetail = new List<CountryDetail>();
countryDetail = GetCountryData();
//Now prepare instance oif datattable
DataTable dt = new DataTable();
dt =
AssignListValueToDataTable(countryDetail);
}
|
Check the
final output in debug mode. Have a look the below output.
Note:
Please download the demo to view the combined code to this article
0 comments:
Please let me know your view