如何将数据源绑定到标签控件(How to bind a datasource to a label control)
将数据源绑定到gridview或repeater之类的东西很容易,但是如何使用标签呢? 下面是我要修改的sql连接。 顺便说一句,我不需要2路绑定。
public void Sql_Connection(string queryString) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(queryString, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); }我正在使用的查询:
SELECT描述FROM RbSpecials WHERE Active = 1
It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.
public void Sql_Connection(string queryString) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(queryString, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); }The query I'm using:
SELECT Description FROM RbSpecials WHERE Active=1
最满意答案
public string SqlConnection(string queryString) { using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = queryString; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // This will return the first result // but there might be other return reader.GetString(0); } } return null; } }这还将确保在异常情况下处理所有一次性对象并将SQLConnection正确地返回到连接池以便重复使用。
最后分配标签的Text属性:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1"); public string SqlConnection(string queryString) { using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = queryString; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // This will return the first result // but there might be other return reader.GetString(0); } } return null; } }This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.
And finally assign the Text property of the label:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");更多推荐
发布评论