首页 > 解决方案 > '无法对 System.Single 和 System.String 执行 'Like' 操作。

问题描述

我正在使用 access 数据库作为数据源构建一个 win 表单应用程序,并且在我的 winform 的搜索按钮中我有这个代码”

private void searchAccessDatabase()
        {
            if (string.IsNullOrEmpty(KeywordTextBox.Text.Trim()))
            {
                Refreshdata();
                return;
            }
            string strkeyword = KeywordTextBox.Text.Trim().ToString();

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("(Convert(ID,'System.String') LIKE '" + "{0}" + "')", strkeyword);
            sb.AppendFormat("OR (Customer_Name LIKE '*" + "{0}" + "*')", strkeyword);
            sb.AppendFormat("OR (Complaint_Number LIKE '*" + "{0}" + "*')", strkeyword);
            sb.AppendFormat("(Convert(Size,'System.String') LIKE '" + "{0}" + "')", strkeyword);
            sb.AppendFormat("OR (Material_Number LIKE '*" + "{0}" + "*')", strkeyword);
            sb.AppendFormat("OR (Nature_Of_Problem LIKE '*" + "{0}" + "*')", strkeyword);
            sb.AppendFormat("OR (Spool_Type LIKE '*" + "{0}" + "*')", strkeyword);
            string strFilter = sb.ToString();
           material_Return_DataBindingSource.Filter = strFilter;

            if (material_Return_DataBindingSource.Count != 0)
            {
                dataGridView1.DataSource = material_Return_DataBindingSource;
            }
            else
            {
                MessageBox.Show("No Records Found", "Search Result", MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);

                Refreshdata();
                return;
            }
        }

但在运行过程中,出现以下错误:“无法对 System.Single 和 System.String 执行 'Like' 操作。”

我知道该错误与单元格的格式类型和我正在使用的搜索类型有关,但我无法更正它们,因为我仍在学习这一点:任何人都请纠正我的错误。

这是样本数据表:它将帮助您查看我输入到表中的样本数据,我想用它来搜索 样本数据表

标签: c#winformsms-accesssql-like

解决方案


  1. 使用和不使用 convert 语句进行测试
  2. 您没有任何 * 来表示字符串相似性可以结束的位置,例如:Name LIKE '*test*'将在 Name 字段中获取每条带有 test 的记录,无论它之前或之后是什么,在哪里Name LIKE 'test*只会让您得到 Name 字段以 test 开头的那些。

您说它“像”没有任何通配符或其他指示符的事实可能会导致问题。

试着让它们相等,看看它是否出错。

此外,您不需要字符串格式中的 + 来处理多个字符串,因为 sb.format 没有它们就可以工作。

 sb.AppendFormat("(Convert(ID,'System.String') LIKE '" + "{0}" + "')", strkeyword);

可以写成

 sb.AppendFormat("(Convert(ID,'System.String') LIKE '{0}')", strkeyword);

我也不认为以下行开头没有和 OR,这可能会导致错误。

 sb.AppendFormat("(Convert(Size,'System.String') LIKE '" + "{0}" + "')", strkeyword);

也许在出错时使用附加结果的最终字符串更新您的问题。


推荐阅读