Convert DataTable To Generic List In ASP.NET MVC

Many times in MVC we need to work with generic list which will be generated from model class ,suppose we are getting data from DataBase in DataTable and thinking to bind view from model class generic list then first we need to convert DataTable into generic list . so let us see how we can achieve this
Suppose the model class is EmpModel.cs as below



public class EmpModel
    {
        [Display(Name = "Id")]
        public int Empid { get; set; }
        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }
        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }

        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }

    }

 Now Class will be look like as follows


public List<EmpModel> GetAllEmployees()
        {
            connection();
            List<EmpModel> EmpList =new List<EmpModel>();

            SqlCommand com = new SqlCommand("GetEmployees", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            con.Open();
            da.Fill(dt);
            con.Close();
            //Bind EmpModel generic list using dataRow 
            foreach (DataRow dr in dt.Rows)
            {

                EmpList.Add(

                    new EmpModel {

                        Empid = Convert.ToInt32(dr["Id"]),
                        Name =Convert.ToString( dr["Name"]),
                        City = Convert.ToString( dr["City"]),
                        Address = Convert.ToString(dr["Address"])

                    }
                    
                    
                    );
            }

            return EmpList;

        }

Please refer below similar article  as above
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me. 

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode