使用sqlQuery C#ASP.NET搜索项目并在gridview中显示

时间:2015-10-13 10:26:52

标签: c# asp.net sql-server search gridview

我无法在gridview中看到任何数据。 无法看到任何搜索结果。 我试图使用sqlparameter。 如您所见,我的sqlQuery是一个很长的。 如果我输入“卡片”,则应该找到带有“大卡片”的item_description'或者'小卡片'值。 这是我的代码:

searchWord = Request.Cookies["Search"].Value;
searchType = Request.Cookies["Display"].Value;
string sqlQuery;
string custSearch = searchWord;

DataTable dt = new DataTable();
SqlConnection sc = new SqlConnection(GetConnectionString());

sqlQuery = "SELECT Player.player_id AS 'ID', Player.fname AS 'First name', "
         +"Player.lname AS 'Last name', Player.sport AS 'Sports',"
         +"Player.position AS 'Position', Player.debut_year AS 'Debut year',"
         +"Player.prof_year AS 'Major year', Player.birth_date AS 'Date of birth'," 
         +"Player.birth_place AS 'Place of birth', Player.team_f AS 'Current team',"
         +"Player.team_s AS 'Past team1', Player.team_t AS 'Past team2',"
         +"Player.living AS 'Death status' " 
         +"FROM Player WHERE (Player.fname LIKE '@SearchPam') "
         +"OR (Player.lname LIKE '@SearchPam') OR (Player.sport LIKE '@SearchPam') "
         +"OR (Player.position LIKE '@SearchPam') OR (Player.team_f LIKE '@SearchPam') "
         +"OR (Player.team_s LIKE '@SearchPam') OR (Player.team_t LIKE '@SearchPam');";
try
{
     sc.Open();
     string result = sqlQuery;
     SqlCommand cmd = new SqlCommand(result, sc);
     cmd.Parameters.AddWithValue("@SearchPam", custSearch);
     SqlDataAdapter adapter = new SqlDataAdapter(cmd);
     DataSet ds = new DataSet();

     adapter.Fill(ds);

     GridView1.DataSource = ds;
     GridView1.DataBind();
}
catch{...}
finally{sc.Close();}

public string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下任一查询,我认为您将使用此获得预期的输出:

string sql = "SELECT * FROM TableA WHERE Col1 LIKE @SearchPam";
.
.
cmd.Parameters.AddWithValue("@SearchPam", "%" + txtSearch.Text + "%");

OR

string sql = "SELECT * FROM TableA WHERE Col1 LIKE '%' + @SearchPam+ '%'";
.
.
cmd.Parameters.AddWithValue("@SearchPam", txtSearch.Text);