开发者

Get SQL data And show it in a text box?

开发者 https://www.devze.com 2023-03-13 07:15 出处:网络
In the last few days I am trying to get data from my SQL table and get it into my textbox. The table name : \"c开发者_运维技巧heck\".

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

The table name : "c开发者_运维技巧heck".

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?


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


 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!


Try this:

TextBox1.AppendText(myReader["columnname"].ToString());
0

精彩评论

暂无评论...
验证码 换一张
取 消