3

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?

3 Answers 3

3
if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

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

Comments

2
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            Console.WriteLine("{0}",rdr.GetString(0));
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.