views:

36

answers:

3

Hi guys,

It's been a long day and I seem to have drawn a blank with my current issue. Below is code contained in my HomeController:

 public ActionResult About()
        {
            SqlDataReader rdr; 
            string fileName = "";
            const string connect = @"Server=localhost;Database=Images;user id=user; password=password;";

            using (var conn = new SqlConnection(connect))
            {

                var qry = "SELECT FileName FROM FileStore";
                var cmd = new SqlCommand(qry, conn);
                conn.Open();
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows)
                {
                    rdr.Read();
                    fileName = rdr["FileName"].ToString();
                }

            }
            return View();
        }

I simply want to display a list of the fileNames from the database in a view. I remember how to do this but I'm stuck on how to write the loop statement that will loop through my sql table.

Can someone point me in the right direction please?

+2  A: 
if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
Lorenzo
+2  A: 
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            Console.WriteLine("{0}",rdr.GetString(0));
        }
    }
anivas
+2  A: 

Do you mean as in while (rdr.Read())?

while (rdr.Read()) 
{ 
    fileName = rdr["FileName"].ToString(); 
}

NOTE: Using this pattern, you don't need .HasRows.

steinar