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());
精彩评论