Friday 20 May 2016

Data Table to List without looping in C#


//function for read data from db
 public DataView Get_DataView(string qry)
    {
       string con="your connection string";
        SqlConnection con = new SqlConnection(constr);
        SqlDataAdapter adp;
        try
        {
            con.Open();
            adp = new SqlDataAdapter(qry, con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            DataTable dt = new DataTable();
            DataView dv = new DataView();
            dt = ds.Tables[0];
            dv = dt.AsDataView();
            return dv;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    } 
//in your controller
DataTable unitDt = Get_DataView("select UNIT_ID,UNIT_NAME from UNIT_MAS ").ToTable();
                List<SelectListItem> unitList = unitDt.AsEnumerable().Select(row => new SelectListItem
                {
                    Value = row.Field<Int32>(0).ToString(),
                    Text = row.Field<string>(1),
                }).ToList();

No comments:

Post a Comment