Skip to content

Connection String Examples ASPX CommandType Text

Ravi Ram edited this page Jul 1, 2020 · 1 revision
 string connectionString = WebConfigurationManager.ConnectionStrings["connName"].ConnectionString;

 List<Courses> courses = new List<Courses>();

    using (SqlConnection conn = new SqlConnection(connectionString)
        {
            string strSql = "SELECT c.Id" +
            ", c.Name" +
            " FROM Course AS c" +
            " WHERE c.Status = 1 AND c.stateAbbr = @stateabbr" +
            " ORDER BY c.Name" ;
            
            SqlCommand cmd = new SqlCommand(strSql, conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@stateabbr", stateabbr);
            //cmd.Parameters.Add("@licenseId", licenseId);

            conn.Open();

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read()){

                    Course course = new Course();
                    course.Id = reader["Id"].ToInt32OrDefault();
                    course.Name = reader["Name"].ToStringOrDefault();

                    courses.Add(course);
                    }
                }

            } //using datareader

        } // using sqlconn
Clone this wiki locally