0

I am trying to display two SQL tables from the same DB in a webpage but the code below is displaying the 'BottomStock' table twice and everything I try seems to either get part of the data from the 'TopStock' table or none at all. I have scroll through countless forums but I have been unable to find a suitable solution. Any help would be appreciated.

public class Test4Model : PageModel
{
    public List<FreezerInfo> listTopFreezer = new List<FreezerInfo>();

    public List<FreezerInfo> listBottomFreezer = new List<FreezerInfo>();

    public void OnGet()
    {
        try
        {
            using (var connection = new SqlConnection("Data Source=SDS- 
LAPTOP\\SQLEXPRESS;Initial Catalog=test;user id=sa;password=wis09"))
            {
                connection.Open();

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM TopStock";
                    command.ExecuteNonQuery();

                    command.CommandText = "SELECT * FROM BottomStock";
                    command.ExecuteNonQuery();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        //reader.Read();
                        {
                            FreezerInfo TopStock = new FreezerInfo();
                            TopStock.Description = reader.GetString(1);
                            TopStock.Quantity = reader.GetString(2);
                            listTopFreezer.Add(TopStock);

                            FreezerInfo BottomStock = new FreezerInfo();
                            BottomStock.Description = reader.GetString(1);
                            BottomStock.Quantity = reader.GetString(2);
                            listBottomFreezer.Add(BottomStock);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }
}

public class FreezerInfo
{
    public string Description { get; set; }
    public string Quantity { get; set; }
}
rgorr
  • 331
  • 3
  • 18
stan780953
  • 15
  • 5
  • You are using the command incorrectly. `ExecuteNonQuery` does not read, only `ExecuteReader` does. You can either do two `SELECT` statements in two commands, reading from each one then do the next command, or you can do two `SELECT` statements in the same command and use `NextResult()` to move to the next `SELECT`. – Charlieface Sep 28 '22 at 21:30
  • Thank you for your reply - Changing ExecuteNonQuery to ExecuteReader results in no data being displayed in the tables. – stan780953 Sep 29 '22 at 06:58
  • 1
    And the other changes I mention? You have two separate batches at the moment, so you would need `using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) {...` on each one. You cannot read them both simultaneously – Charlieface Sep 29 '22 at 09:29
  • I have tried both options and even the one from the suggested answer above to no avail. I either get nothing returned or part of the table. Very frustrating as it would seem what I am asking is possible. – stan780953 Sep 29 '22 at 19:06

1 Answers1

0

You are using SqlCommand completely wrong. ExecuteNonQuery does not return results. Only ExecuteScalar or ExecuteReader do. Furthermore, you have two batches each with a SELECT, but you are only executing one and somehow expecting the results to be interleaved.

I would advise you to use one batch of two SELECT statements, you can use NextResult to move to the next resultset within the batch.

  • Store your connection string in a settings file, not hard-coded.
  • Only select the columns you need, rather than SELECT *.
  • Use column names rather than ordinals, especially if you are using SELECT *.
  • Do not swallow exceptions. Handle them or allow them to bubble back to the caller.
  • Consider using async to allow the caller to continue asynchronously.
  • Reconsider the data types of the columns.
  • Consider why you have two almost identical tables in the first place. Perhaps they should be merged.
public void OnGet()
{
    try
    {
const string query = @"
SELECT Description, Quantity
FROM TopStock;

SELECT Description, Quantity
FROM BottomStock;
";
        using var connection = new SqlConnection(connectionStringFromSettingsFileHere);
        using var command = new SqlCommand(query, connection);
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())

        while (reader.Read())
        {
            FreezerInfo TopStock = new FreezerInfo
            {
                Description = (string)reader["Description"],
                Quantity = (string)reader["Quantity"],  // shouldn't it be an int???
            };
            listTopFreezer.Add(TopStock);
        }

        reader.NextResult();

        while (reader.Read())
        {
            FreezerInfo BottomStock = new FreezerInfo
            {
                Description = (string)reader["Description"];
                Quantity = (string)reader["Quantity"],  // shouldn't it be an int???
            };
            listBottomFreezer.Add(BottomStock);
        }
    }
    catch (Exception ex)
    {
        // exception handling here. DO NOT SWALLOW
    }
}
Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • Thank you for all your time and help, it is very much appreciated. I have adjusted the code but unfortunately, it is displaying nothing in the Html table. The reason I have used two tables with the same info is I thought that would be easier to display the two sets of data via Html. Once again thanks, I think I will give up on this one until my head has stopped hurting. – stan780953 Sep 30 '22 at 14:59
  • You haven't shown anything involving HTML in your question, so this answer fixes the problems shown in your question. Check at least that `listTopFreezer` and `listBottomFreezer` contain the correct data. – Charlieface Sep 30 '22 at 16:50
  • yes, fair point about not showing the HTML code and I also owe you an apology as I had entered the wrong data string. Your code is now returning all the data for the bottom table but only one row for the top. I have checked the query in SQL Management and it returns all the data for the top table correctly. I will post the HTML code in case you can spot something wrong. – stan780953 Sep 30 '22 at 18:08
  • Are you sure you have `while (reader.Read())` on the first list, or is it just `reader.Read()` – Charlieface Oct 01 '22 at 19:10
  • Thank you for all your help. The debugger contained the same value as being displayed in the HTML table. In the end, I created another project and used an ado.net entity data model which allowed me to display the two tables. – stan780953 Oct 04 '22 at 14:05