我有这些包括:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
我的连接字符串是
public partial class Directory : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=10.4.33.61;Initial Catalog=Bank_Reconciliation;Persist Security Info=True;User ID=****;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
我按字符串搜索并在数据网格视图中显示的方法(将搜索按钮命名为btnsearch
)是
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%' + @search + '%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("@search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
我收到以下错误:
必须声明标量变量" @ Name"。
为什么会这样,我该如何解决?
答案 0 :(得分:0)
让TSQL使用LIKE @search可能更容易,并在添加参数时处理它:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = @"SELECT * FROM Employee WHERE Name LIKE @search";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.AddWithValue("@search", "%" + txtSearch.Text + "%");
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
答案 1 :(得分:0)
将按钮点击代码更改为:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%" + @search + "%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("@search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataTable dt = new DataTable();
da.Fill(ds, dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
它为like运算符提供了正确的引号,并且还使用了DataTable而不是DataSet。您也可以使用DataSet,但这里似乎没有必要。