Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SQL data And show it in a text box?

In the last few days I am trying to get data from my SQL table and get it into my textbox.

The table name : "check".

The code I am using :

SqlDataReader myReader = null;

connection = new SqlConnection(System.Configuration.ConfigurationManager
                    .ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();

var command = new SqlCommand("SELECT * FROM [check]", connection);
myReader = command.ExecuteReader();
while (myReader.Read())
{
    TextBox1.Text = myReader.ToString();
}
connection.Close();

I am getting nothing as a result. Anyone know why? Maybe I am not calling the SQL correctly?

like image 869
Alon M Avatar asked Jan 19 '23 12:01

Alon M


2 Answers

using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = "SELECT ColumnName FROM [check]";
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
            TextBox1.Text = reader["ColumnName"].ToString();
    }
}

Some comments:

  • don't use *, specify only those fields that you need
  • use using - less code, guaranteed disposal
  • I assume this is a test program, otherwise it does not make sense to reset Text to a in the loop
like image 154
Alex Aza Avatar answered Jan 29 '23 09:01

Alex Aza


 TextBox1.Text = myReader["fieldname"].ToString();

also I think you can change while with if because for every row from your table you'll overwrite textbox text!

like image 39
danyolgiax Avatar answered Jan 29 '23 09:01

danyolgiax