Saturday 10 May 2014

Convert DataTable to List<> C#

public class ClsCountry
    {
        public int iCountryID { get; set; }
        public string vchCountryName { get; set; }
        public Nullable<bool> bActive { get; set; }
        public string vchEntryDate { get; set; }
        public string vchUpdateDate { get; set; }
    }

//Method which will return List of Country type (class)
public static List<ClsCountryy> SelectAllCountries()
        {
            List<ClsCountry> lstCountry = new List<ClsCountry>();
            DataTable dtCountries = new DataTable();
            SqlConnection conn = new SqlConnection(ConnString);
            SqlDataAdapter da = new SqlDataAdapter("select * from tblCountries", conn);
            
            try
            {
                da.Fill(dtCountries);
            }
            catch
            {
                return lstCountry;
            }
            //DATATABLE TO LIST CONVERSION
            foreach (DataRow dr in dtCountries.Rows)
            {
                lstmstCountry.Add(new ClsCountry 
                { 
                    iCountryID = Convert.ToInt16(dr["iCountryID"]),
                    vchCountryName = dr["vchCountryName"].ToString(),
                    bActive = Convert.ToBoolean( dr["bActive"]),
                    vchEntryDate = dr["vchEntryDate"].ToString(), 
                    vchUpdateDate = dr["vchUpdateDate"].ToString() 
                });
            }
            return lstCountry;
        }

No comments:

Post a Comment