【发布时间】:2023-03-31 17:25:01
【问题描述】:
我正在尝试从绑定到 SQL 数据连接的GridView 控件中过滤搜索数据,但我没有任何成功。每当我尝试搜索某些内容时,都会导致找不到任何记录。这是我的主要搜索代码:
public void FilterGridView(string column, string terms) //SELECT * FROM [Table_1] WHERE [First Name] LIKE '%valuetosearchfor%' is the format to use here
{
DataTable filterTable = new DataTable(); //create a datatable to hold the data while we retrieve it
SqlConnection connection = new SqlConnection("Data Source=TAMUWINPART\\SQLEXPRESS;Initial Catalog=phpMyWorkers;Integrated Security=True"); //connect to SQL
try
{
connection.Open(); //open the connection
string filterStatement = "SELECT * FROM [Table_1] WHERE @column LIKE '%@terms%'"; //select all from table_1 with the correct column name / terms
SqlCommand sqlCmd = new SqlCommand(filterStatement, connection); //make a sql command
sqlCmd.CommandType = CommandType.Text; //make it an average joe sql text command
//define the @ sql variables
sqlCmd.Parameters.AddWithValue("@column", column);
sqlCmd.Parameters.AddWithValue("@terms", terms);
SqlDataAdapter filterAdapter = new SqlDataAdapter(sqlCmd); //make a data adapter to get all the data from the command and put it into the data table
filterAdapter.Fill(filterTable); //fill the data table with the data from the SQL connection
if(filterTable.Rows.Count > 0) //if records were found relating to the terms
{
//if records WERE found
workersView.DataSource = filterTable; //set the data source to this instead
workersView.DataBind(); //refresh the data
}
else
{
//no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
}
}
catch (System.Data.SqlClient.SqlException ex) //if the thing just decides that it doesn't want to work today
{
string msg = "myWorkers had a problem fetching the data : ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close(); //close the connection
}
}
public void FilterSearchButton_Click(object sender, EventArgs e) //when someone clicks the button to filtersearch the gridviews
{
string column = FilterSearchDropdown.SelectedValue.ToString(); //get the column that the user wants to filter by and make sure it's a string
string terms = FilterSearchTerms.Text; //get the terms to search by - verified string for sure
FilterGridView(column, terms);
}
public void FilterRemoveButton_Click(object sender, EventArgs e) //when someone decides to remove the filter
{
BindGridView(); //refresh the gridview based on all of the data
FilterSearchTerms.Text = ""; //remove the text from the filter search terms box
}
这是一张布局的图片。
即使我搜索真实数据,它也会导致这个被调用
else
{
//no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
}
表示数据表的行数为0...
有人知道为什么吗?谢谢。
【问题讨论】:
标签: c# asp.net sql-server search ado.net