【问题标题】:C# Filter DataGridView with multiple textboxes?C# 使用多个文本框过滤 DataGridView?
【发布时间】:2018-04-30 02:22:47
【问题描述】:

这就是它的样子。学生查找和课程查找搜索两个不同的数据库。我正在尝试从左侧的文本框中显示搜索结果。这是数据库的样子。

此代码在用户单击提交时运行。我从另一个帖子中检索到它,但无济于事:

BindingSource bs = new BindingSource();
        bs.DataSource = dgvAdvisor.DataSource;
        bs.Filter = "First_Name like '%" + lblFirstName.Text + "%' AND 
        Username like '%" + lblUsername.Text + "%'";
        dgvAdvisor.DataSource = bs;

第 3 行和第 4 行是一行,Stack Overflow 似乎把它切碎了。

有什么建议吗?

【问题讨论】:

  • 这段代码到底遇到了什么问题?
  • 另外,你想让名字看起来像 lblFirstName 的文本,lblFirstNameTextBoxLabel
  • @Amit 问题是我无法从文本框中获得过滤搜索的结果,但现在我意识到我什至没有填充表格的 datagridview。
  • 我的第二条评论呢,lblFirstName 是标签还是文本框。你说你没有填充表格的数据网格视图,是因为你的数据源中的这个问题吗?
  • 一种懒惰的方法是通过 sql 查询而不是使用 C# 代码对其进行过滤。只需在任一按钮或事件中插入查询即可。

标签: c# sql winforms


【解决方案1】:

从您提供的代码来看,您似乎正在使用 Label 的文本过滤数据源,并且您希望使用 TextBox 的文本对其进行过滤。

假设您关联的 TextBox 控件是 txtFirstNametxtUserName , 尝试如下修改您的代码。

    BindingSource bs = new BindingSource();
    bs.DataSource = GetDataTable(); //This method should return whole data table.
    bs.Filter = "First_Name like '%" + txtFirstName.Text + "%' AND 
    Username like '%" + txtUserName.Text + "%'";
    dgvAdvisor.DataSource = bs;

【讨论】:

  • 我觉得这绝对是解决办法,但我现在意识到我什至没有将我的 DataGridView 链接到我的表。我觉得我使用 BindingSource 不正确。顺便谢谢你的帮助。
  • @tryingtotryhard 首先将BindingSourceDataSouce 绑定到DataTable 吗?在您的代码中,我没有看到那部分。它应该看起来像bs.DataSource = GetDataTable() 假设 GetDataTable 方法返回您有问题显示的数据表。相应地编辑了我的答案
  • @tryingtotryhard this article 可能会为您提供更多帮助。
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多