c# - Fill generic list from SqlDataReader

前端 未结 5 1862
轮回少年
轮回少年 2021-02-14 02:23

How can I add values that a SqlDataReader returns to a generic List? I have a method where I use SqlDataReader to get CategoryID from a

5条回答
  •  不思量自难忘°
    2021-02-14 02:42

    AS BrokenGlass explained this is the demonstration

    SqlConnection connection = null;
            SqlDataReader dr= null;
            SqlCommand cmd = null;
    List catID = new List();
            try
            {
                connection = new SqlConnection(connectionString);
                cmd = new SqlCommand("select CategoryID from Categories", connection );
    
                connection.Open();
    
    
    
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
                }
    
    
            }
            finally
            {
                if (connection  != null)
                    connection.Close();
            }
            return catID;
    

    as well as you change the declaration

    SqlDataReader reader = null;
    

    to

    SqlDataReader dr= null; // Because you are using dr in the code not reader
    

提交回复
热议问题