21 January 2014

How to convert DataTable to List of Class in C#.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Employeeservice
{
    class employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string city { get; set; }
    }
}
    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Employeeservice
{
   public class EmployeeService : IEmployeeService
    {
      private List<employee> TestForEach(DataTable table)
        {
         string ConStr = "Server=.;Database=adi;User Id=sa;Password=password;";
          SqlConnection con = new SqlConnection(ConStr);
         con.Open();
           cmd = new SqlCommand("SELECT * FROM tbl_employee", con);
           sda = new SqlDataAdapter(cmd);
           dt = new DataTable("Employee");
           sda.Fill(dt);
           var employeeList = new List<employee>(table.Rows.Count);
           foreach (DataRow row in table.Rows)
              {
              var values = row.ItemArray;
              var category = new employee()
               {
             Id = Convert.ToInt32(values[0]),
                  Name =Convert.ToString( values[1]),
                  city =Convert.ToString(values[2]),
                };
              employeeList.Add(category);
            }
         return employeeList;
        }
    }
}

No comments:

Post a Comment