如何将数据源绑定到标签控件(How to bind a datasource to a label control)

编程入门 行业动态 更新时间:2024-10-12 05:49:02
如何将数据源绑定到标签控件(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");

更多推荐

本文发布于:2023-07-28 03:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299887.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据源   绑定   控件   如何将   标签

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!