我有一个主窗体(formMain),它在其加载事件中加载用户控件(分类)。并且在用户控件分类的加载事件中它显示一个datagridview。让我给你看一下代码。 分类
string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";
private void load_data()
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
幸运的是它正在工作,但是当我单击位于另一个用户控件(搜索)中的搜索按钮时,它会在主窗体(formMain)中引发一个事件,其中它必须过滤用户控件(分类)中的 datagridview,但我的代码不起作用。也许我的字符串查询中有语法错误。这是代码。
主要形式
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
classification control = new classification();
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%@search'";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//MessageBox.Show(content.txtboxSearch.Text);
cmd.Parameters.AddWithValue("@search", content.txtboxSearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}