【问题标题】:WinForm DataGridView Sorting by string from column c#WinForm DataGridView按列c#中的字符串排序
【发布时间】:2016-06-06 23:42:25
【问题描述】:

我正在尝试通过从文本框中搜索字符串来过滤 datagridview 中包含数千个条目的表,该字符串受从组合框中选择的列名的限制。我希望搜索实时发生,通过 textbox_TextChanged 类进行更新。通过研究,我编写了一些应该做我需要的代码。但是,每当我在文本框中输入,提示 textchanged 类时,都会出现错误:

“抛出异常:System.Data.dll 中的‘System.Data.SyntaxErrorException’”

请注意,datagridview 确实会在输入文本框之前显示所有数据条目,并且组合框选项与 datagridview 中的列的大小写完全相同。

我的代码:

private void searchTerms_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = shareholderDataGrid.DataSource;
        bs.Filter = string.Format(searchItem + " like '%{0}%'", searchTerms.Text.Trim().Replace("'", "''"));
        shareholderDataGrid.DataSource = bs;
    }

shareholderDataGrid 是数据网格,searchItem 是指从组合框中选择的字符串,searchTerms 是指用户输入的文本框。

感谢任何帮助,如果您需要更多信息,请询问。

【问题讨论】:

  • @cjpartin,抛出异常时string.Format(searchItem ... )的值是多少?
  • 不管组合框中选择的选项如何,都会抛出它。选项是“ID”、“姓氏”、“名字”。这些是 searchItem 的值。

标签: c# .net winforms datagridview


【解决方案1】:

我认为问题可能在于您致电.Replace("'", "''")。你试过没有吗?

【讨论】:

  • 我刚试过,没有运气。提到列名是 ID、姓氏和名字可能会有所帮助。这些也是组合框中选项的名称。
  • 异常出现可靠吗?显而易见的问题是列名中的空格是否会导致语法错误,但在选择 ID 时不应该发生这种情况。
  • 是的,它总是在文本框中输入单个字符后抛出。无论选择哪种列。
【解决方案2】:

我发现它为什么会抛出那个异常! 数据源中的列名中有空格,当我对组合框执行相同操作时,它搞砸了。在编辑访问数据库表以使列没有空格,并将这些相同的更改放在组合框中的选项中时,它已得到修复。它完美无缺。这是我使用的最终代码,因为一个不相关的错误,我不得不制作一个全新的 Visual Studio 项目。

private void searchBox_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = string.Format(columnChoice.Text + " LIKE '*{0}*'", searchBox.Text.Trim().Replace("'","''"));
        dataGridView1.DataSource = bs;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多