简体   繁体   中英

Retrieve all rows from SQL Server and place into multiline textbox

I want to retrieve all rows from SQL Server and to place it in a multi line textbox. The query executes but it loads the last row maybe because its the last record. Should I have a 'foreach' statement?

private void LoadComments()
{
   using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_TestDBConnectionString"].ConnectionString))
   {
      using (SqlCommand com = new SqlCommand("LoadNotes", con))
      {
         com.CommandType = CommandType.StoredProcedure;

         con.Open();

         com.ExecuteNonQuery();

         SqlDataReader dr = com.ExecuteReader();

         while (dr.Read() == true)
         {
            TextBox1.Text = dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + dr.GetValue(2).ToString();
         }
      }
   }
}

Before While loop set TextBox1.Text=""; then try this code.

TextBox1.Text += dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + 
dr.GetValue(2).ToString()+Enviroment.NewLine;

In your Code your assingning each row to TextBox1 but you to concate the next row to TextBox1 so i put + before equal so it concate all rows.

string str = "";

while (dr.Read() == true)
         {
           str+= dr.GetValue(0).ToString() + " " + dr.GetValue(1).ToString() + dr.GetValue(2).ToString();
         }

 TextBox1.Text = str;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM