使用组合框在datagrid中搜索

时间:2013-09-19 05:44:02

标签: c# datagridview

我必须使用c#从datagrid中的文本框中搜索数据 我的代码是

          private void button_Search_Click(object sender, EventArgs e)
    {
        sqlcon.Open();
        //DataSet ds15 = new DataSet();

  DataTable dt= new DataTable();                        

 SqlDataAdapter adpt = new SqlDataAdapter("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text); 
  adpt.Fill(dt);//datatable to catch the fields from the database
 dataGridView1.DataSource = dt;

获取错误争议异常未得到处理

我想搜索组合框

4 个答案:

答案 0 :(得分:1)

没有构造函数匹配SqlDataAdapter

上的参数
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from TableName where Field like '%{0}%'", 
                 comboBox_Search.Text), sqlcon);

答案 1 :(得分:1)

每次查询数据库都不是一种更好的方法。而是取一个BindingSource对象并填充一次源。然后使用BindingSource.Filter属性获取相关结果集并将结果集绑定到grid。

查看thisthis链接。

此外,要解决您的问题,您可以尝试这样:

....
sqlcon.Open();
string query  = string.Format("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
SqlCommand cm = new SqlCommand(query, sqlcon);
SqlDataAdapter adpt = new SqlDataAdapter(cmd); 
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
....

答案 2 :(得分:0)

SqlDataAdapter如何知道从哪里获得结果?

您没有正确初始化SqlDataAdapter的构造函数。第一个参数是完整的select语句,第二个参数是你的连接字符串。

SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from atm_status where Table like '%{0}%'", comboBox_Search.Text), sqlcon);

答案 3 :(得分:0)

private void txt_Searchque_TextChanged(object sender, EventArgs e)
{
    string connector_string = "datasource = localhost;port=3306;username=root;password=;";
    MySqlConnection sqlcon = new MySqlConnection(connector_string);
    sqlcon.Open();
    string query = string.Format("Select * from oep.quiz where que like '%{0}%'", txt_Searchque.Text);
    MySqlCommand cmd = new MySqlCommand(query, sqlcon);
    MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    adpt.Fill(dt);
    dataGridView1.DataSource = dt;
}