Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public class ContinentDataAccessLayer
{
  public static List<continent> GetAllContinents()
  {
    List<continent> listContinents = new List<continent>();
    
    string CS = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
      SqlCommand cmd = new SqlCommand("Select CountryName from country", con);
      con.Open();
      SqlDataReader rdr = cmd.ExecuteReader();
      while (rdr.Read())
      {
        Continent continent = new Continent();
        continent.ContinentId = Convert.ToInt32(rdr["CountryID"]);
        // System.IndexOutOfRangeException: CountryID
        continent.ContinentName = rdr["CountryName"].ToString();
    
        listContinents.Add(continent);
      }
    }

    return listContinents;
  }
}
Posted
Updated 18-May-14 0:50am
v2

You are selecting only CountryName in your SQL query, but later try to access CountryID...
Update your SQL to select also CountryID
SQL
Select CountryName, CountryID from country
 
Share this answer
 
Comments
DamithSL 18-May-14 8:20am    
my5!
Kornfeld Eliyahu Peter 18-May-14 8:22am    
Thank you...
your query doesn't return a column named 'CountryID'. change your query into

Select CountryName, CountryID from country


moreover you can use the debugger for such issues.
step over-F10
step into-F11
breakpoint-F9
start debug-F5

so on.
 
Share this answer
 
Comments
DamithSL 18-May-14 8:21am    
my5!
Vedat Ozan Oner 18-May-14 8:35am    
thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900