更好的方式来创建的StoredProcedure
SP:
Create proc sp_Search(@txtSearch nvarchar(150))
as begin
SELECT * from tenant WHERE name like @txtSearch+'%'
end
后面的代码:
string txtSearch = txtSearchRP.Text;
SqlDataReader dr;
using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("@txtSearch", txtSearch);
cmdd.Connection = conn;
conn.Open();
dr = cmdd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
var name = dr["name"].ToString();
var location = dr["location"].ToString();
}
} dr.Close();
conn.Close();
}
}
更新时间: 写返回的数据表的功能,使我们可以把它绑定到我们的GridView控件正如我在代码做了以下
public DataTable bindGridView()
{
string txtSearch = txtSearchRP.Text;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
SqlCommand cmdd = new SqlCommand();
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("@txtSearch", txtSearch);
cmdd.Connection = con;
con.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmdd);
DataSet ds = new DataSet();
dap.Fill(ds);
dt = ds.Tables[0];
con.Close();
}
return dt;
}
开按钮点击:调用bindGridView()函数进行绑定Gridview控件
GridView1.DataSource = bindGridView();
GridView1.DataBind();
只需将_MAX'S_中的单引号替换为两个单引号,即_name LIKE'%MAX''%'_ – bjan 2014-10-10 04:32:32
感谢您的回复,请注意类似的操作符必须基于搜索框(用户输入) - txtSearcRP.Text。我如何使用你提出的答案修改(名称LIKE'%“+ txtSearchRP.Text +”%')? – rickyProgrammer 2014-10-10 04:44:38
使用String的替换方法 – bjan 2014-10-10 04:48:35