Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop through database table .net c#

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?

like image 799
109221793 Avatar asked Feb 28 '26 03:02

109221793


2 Answers

if (rdr.HasRows) {
    while (rdr.Read()) {
        fileName = rdr["FileName"].ToString();
    }
}
like image 89
Lorenzo Avatar answered Mar 02 '26 20:03

Lorenzo


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

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

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

like image 20
steinar Avatar answered Mar 02 '26 21:03

steinar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!