1

The same query works fine in SQL Server. I need it to return all rows read from the DB table in c#.

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = @"SELECT TypeName, Sum(HitNo) FROM TypeHit GROUP BY TypeName";

SqlDataReader sdr = cmd1.ExecuteReader();
sdr.Read();

if (sdr.HasRows)
{
   while (sdr.Read())
   {
       TextBox1.Text = sdr.GetString(0) +" at " + sdr.GetInt32(1);
   }
}

3 Answers 3

1

Why are you using sdr.Read(), that will advance the reader to the next block of data?

DataReader.Read Method

You're also overwriting the TextBox'-Text property for every record in the reader since while (sdr.Read()) is a loop.

using(SqlDataReader sdr = cmd1.ExecuteReader())
{
        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                TextBox1.Text += sdr.GetString(0) + " at " + sdr.GetInt32(1) + Environment.NewLine;
            }
        }
        else
        {
            TextBox1.Text = "No rows found.";
        }
}

Retrieving Data Using a DataReader (ADO.NET)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to append result in loop:

TextBox1.Text = TextBox1.Text+sdr.GetString(0) +" at " + sdr.GetInt32(1);

Also, from performance point of view, it's better to use StringBuilder:

StringBuilder bld = new StringBuilder();
if (sdr.HasRows)    
{    
   while (sdr.Read())    
   {    
      bld.Append(sdr.GetString(0));
      bld.Append(" at ");
      bld.Append(sdr.GetInt32(1));    
    }    
 }
 TextBox1.Text = bld.ToString();

1 Comment

I have tried that it do not work, even when I count the number of rows the sdr returns it is just one
0

In each loop you replace the last TextBox1.Text with the data fetched.
So you end up with only the last line. If you need to see all the results you need something like this.

   StringBuilder sb = new StringBuilder();
   while (sdr.Read()) 
   { 
       sp.AppendLine(sdr.GetString(0) +" at " + sdr.GetInt32(1)); 
   } 
   TextBox1.Text = sb.ToString();

also change the TextBox MultiLine property to True and resize the TextBox1 to show more than one line

ouch ... missed the bogus sdr.Read() before loop....

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.