必须声明标量变量"@Name"; [英] Must declare the scalar variable "@Name"
本文介绍了必须声明标量变量"@Name";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些包括:
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
)是
My method to search by string and display in data grid view (naming search button as btnsearch
) is
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".
Must declare the scalar variable "@Name".
这是为什么,如何解决?
Why is this, and how do I fix it?
推荐答案
将您的按钮单击代码更改为此:
Change you button click code to this:
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,但在这里似乎不需要.
It puts proper quotes for like operator, and also used DataTable instead of DataSet. You can also use DataSet but here it seems no need for that.
这篇关于必须声明标量变量"@Name";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文