Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c# - Cannot perform 'Like' operation on System.Int32 and System.String. DataGridView search and filter

I have a form that when I select a column name from a ComboBox, and type in a text box it filters and displays the searched criteria in the DataGridView. When I search for "Reference" which is an int data type, which is also identity, and primary key. I get the error message :

"Cannot perform 'Like' operation on System.Int32 and System.String."

My code is

DataTable dt;
private void searchForm_Load(object sender, EventArgs e)
{
    SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|LWADataBase.sdf;");
    SqlCeDataAdapter sda = new SqlCeDataAdapter("select * from customersTBL", con);
    dt = new DataTable();
    sda.Fill(dt);
    dataGridView1.DataSource = dt;
    comboSearch.Items.Add("[Reference]");
    comboSearch.Items.Add("[First Name]");
    comboSearch.Items.Add("[Surename]");
    comboSearch.Items.Add("[Address Line 1]");
    comboSearch.Items.Add("[Address Line 2]");
    comboSearch.Items.Add("[County]");
    comboSearch.Items.Add("[Post Code]");
    comboSearch.Items.Add("[Contact Number]");
    comboSearch.Items.Add("[Email Address]");


}


private void searchTxt_TextChanged(object sender, EventArgs e)
{
    if (comboSearch.SelectedItem == null)
    {
        searchTxt.ReadOnly = true;
        MessageBox.Show("Please select a search criteria");
    }



    else
    {
        searchTxt.ReadOnly = false;
        DataView dv = new DataView(dt);
        dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
        dataGridView1.DataSource = dv;

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Convert the number to a string inside the filter:

dv.RowFilter = string.Format("CONVERT({0}, System.String) like '%{1}%'",
                             comboSearch.Text.Trim(), searchTxt.Text.Trim());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...