如何将数据库中查询出来的值赋给textbox

各位大侠

小弟刚刚接触C# 问个比较没营养的问题

如何将从数据库中查询出来的字段值分别显示到textbox控件中

感激不尽

不同的开发语言代码不同,以C# WINFORM为例:
方法一、数据绑定
首先连接数据库,读取数据 绑定控件 textbox1.text=数据库取出值

方法二、写代码
//sql语句string sql = string.Format("SELECT text FROM Test WHERE ID = {0})", 1);
//数据库名为Temp.mdb,表为Test,包含2个字段:ID 和 text
string DbConnectionString = "Data Source=Computer-PC;User ID=sa;Password=123456;Initial Catalog=Temp;Pooling=true";
SqlConnection con = new SqlConnection(DbConnectionString);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();

textBox1.Text = myReader["text"].ToString();

MessageBox.Show("完成!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Cancel();
myReader.Close();
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-05-22
//估计还没有学三层 所以就用这个吧
string connstr=ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;//web.config里面去配
public SqlConnection GetConn()
{
return new SqlConnection(connstr);
}
public void BindData()
{
string id="";
string name = "";
using (SqlConnection c = GetConn())
{

string sqlString = "select id,name from xxx where id=5";
SqlCommand cmd = new SqlCommand(sqlString, c);
c.Open();
SqlDataReader r = cmd.ExecuteReader();

if (r.Read())//如果有多条就 while 那样绑定时候就得筛选了
{
//XClass x = new XClass();
id = r.GetString(0);
name = r.GetString(1);
}
}
this.tbxId = id;
this.tbxName = name;
}本回答被提问者和网友采纳
第2个回答  2010-08-10
textbox1.text=查出来的值。也就是把查出来的值直接赋给textbox的text属性就行了。不知道你是不是想要这样的效果
第3个回答  2010-08-08
数据绑定里面的吧
相似回答