首页 > 解决方案 > 使用多文本框窗口形式搜索 C#

问题描述

public void filter()  
{  
    using (SqlConnection sqlconn = new SqlConnection(@"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))  
    {  
         SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);  
         DataTable dtbl = new DataTable();  
         sqlad.Fill(dtbl);  
         DataView dv = dtbl.DefaultView;  
         dv.RowFilter = string.Format("Name like '%{0}%' and Address like '%{0}% and  office_number like '" + searchoffice.Text + "%'and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text,searchoffice.Text,searchphone.Text,searchaccountname.Text);  
            customergrid.DataSource = dv.ToTable();  
            dtbl.DefaultView.Sort = "[Name] DESC";  
    }  
}  

textbox.textchange()当我在-EventHandler中运行此方法时,我得到以下异常:

The expression contains an invalid string constant: '

请帮我修复异常。

标签: c#sql-serverwindows-forms-designer

解决方案


似乎您的查询字符串在 附近缺少一个空格office_number like '" + searchoffice.Text + "%' and phone_number,还缺少一个 '-字符并且 String.Format- 参数计数不匹配。

所以尝试以下:

public void filter()  
    {  
        using (SqlConnection sqlconn = new SqlConnection(@"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))  
        { 
            SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);  
            DataTable dtbl = new DataTable();  
            sqlad.Fill(dtbl);  
            DataView dv = dtbl.DefaultView;  
            dv.RowFilter = string.Format("Name like '%{0}%' and Address like ‘%{1}%’ and  office_number like '" + searchoffice.Text + "%' and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text);  
            customergrid.DataSource = dv.ToTable();  
            dtbl.DefaultView.Sort = "[Name] DESC";  
        }  
    } 

推荐阅读