c#关于DataGridView利用TextBox输入内容进行查询的问题

来源:百度知道 编辑:UC知道 时间:2024/05/10 23:46:16
比如我的数据库数据有张表Users里面有两列Id,NickName
比如存放2条数据[1000|风筝]和[1001|大叔]
在TextBox中输入[风筝]然后点Button查询
但是data.Fill(dataset, "Users");这里报错
不知道哪里写错了~~~
代码如下↓
private void button1_Click(object sender, EventArgs e)
{
GetSeach();
}
private void GetSeach()
{
DataSet dataset = new DataSet();
string sql =string.Format( "select Id,NickName from Users where NickName={0}",textBox1.Text.Trim());
SqlDataAdapter data = new SqlDataAdapter(sql, 数据库连接字符串);
data.Fill(dataset, "Users");
dgv1.DataSource = dataset.Tables["Users"];
}
我在TextBox里输入Id列的数据1000,可以正常查询
但是输入NickName列的数据 大叔 就报错
不知道那里写错了

string sql =string.Format( "select Id,NickName from Users where NickName={0}",textBox1.Text.Trim());

修改

string sql =string.Format( "select Id,NickName from Users where NickName='{0}'",textBox1.Text.Trim());

或者

string sql "select Id,NickName from Users where NickName='"+textBox1.Text.Trim()+"'"

Sql 语句有问题.!

{0} 少了两个点引号哦. ! 呵呵 ,是不是粗心了吧?

string sql =string.Format("select Id,NickName from Users where NickName='{0}'",textBox1.Text.Trim());

因为NickName是字符串型,必须加上引号才行...!

汉字的要加‘’号