Foreach loop through .net c # database table

It was a long day, and I seem to have drawn a space with my current problem. The following is the 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 just want to display a list of file names from the database in the view. I remember how to do this, but I was fixated on how to write a loop statement that will go through my sql table.

Can someone point me in the right direction?

+3
source share
3 answers
if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
+3
source

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

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

NOTE. Using this template you do not need .HasRows.

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

Source: https://habr.com/ru/post/1772202/


All Articles