Sunday, August 31, 2014

How to Get SqlDataReader, OdbcDataReader, OracleDataReader in List


Step 1: Create Class

 public class Student
        {
            public string Name { get; set; }
            public int RollNo { get; set; }
            public string Address { get; set; }
            public DateTime AdmissionDate { get; set; }         
        }

Step 2: Create Function 

string conStr = ConfigurationManager.ConnectionString["StudentConnection"].ToString();

public List<Student> GetStudents()
{
 using(OdbcConnection con=new OdbcConnection(conStr))
 {
  OdbcCommand cmd = new OdbcCommand();
  cmd.CommandText = "Select * from dbo.Students;
  cmd.Connection = con;
  con.Open();
  OdbcDataReader dr=cmd.ExecuteReader();

  List<SSRSEntity> listData = new List<SSRSEntity>();
  while (dr.Read()) 
   {
//Sometimes the value is null so it throw error during conversion that's why not using the uper 3 lines of code
// object.property = datareader.if null at index 0 then assign "" empty to string

   o.Name = dr.IsDBNull(0) ? "" : (string)dr.GetValue(0);
   o.Address = dr.IsDBNull(1) ? "" : (string)dr.GetValue(1);
   o.RollNo = dr.IsDBNull(2) ? "" : (int)dr.GetValue(2);
 o.AdmissionDate =Convert.ToDateTime((string)dr["SubmitDateTime"]);
                    
  listData.Add(o);
}
  return listData;
    }     
}

No comments:

Post a Comment

Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx protected void Application_BeginRequest(object sender,EventArgs e)     {         //to remove x frame         Resp...