首页 > 解决方案 > 在任何文本框中的任何更改上更新过滤器和 DataGrid

问题描述

我有 4 个文本框。我将它们中的每一个用作 DataGrid 的过滤器参数。问题是我必须用 IF 函数覆盖所有可能的变体,以使它们正常工作。有没有更好的方法来做到这一点?

下面是一个示例,它甚至没有涵盖所有变体。我还需要分别为每个 texbox 修改它。

这是代码:

    private void BusinessIDSearch_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        _conditions["name"] = null;

        if (!string.IsNullOrEmpty(BusinessIDSearch.Text))
        {
            _conditions["name"] = string.Format("LY Like '{0}%'", BusinessIDSearch.Text);
            UpdateFilter();
            FICount.Content = DataGrid1.Items.Count;
        }
        if (!string.IsNullOrEmpty(NameSearch.Text) && string.IsNullOrEmpty(BusinessIDSearch.Text))
        {
            _conditions["name"] = string.Format("HAKUNIMI Like '%{0}%' AND LY Like '%{1}%'", NameSearch.Text, BusinessIDSearch.Text);
            UpdateFilter();
            FICount.Content = DataGrid1.Items.Count;
        }
        if (!string.IsNullOrEmpty(NameSearch.Text) && !string.IsNullOrEmpty(GroupSearch.Text))
        {
            _conditions["name"] = string.Format("HAKUNIMI Like '%{0}%' AND KONSERNI Like '%{1}%' AND YRNRO Like '{2}%'", NameSearch.Text, GroupSearch.Text, IDSearch.Text);
            UpdateFilter();
            FICount.Content = DataGrid1.Items.Count;
        }
        if (!string.IsNullOrEmpty(BusinessIDSearch.Text) && !string.IsNullOrEmpty(GroupSearch.Text) && !string.IsNullOrEmpty(NameSearch.Text) && !string.IsNullOrEmpty(IDSearch.Text))
        {
            _conditions["name"] = string.Format("HAKUNIMI Like '%{0}%' AND KONSERNI Like '%{1}%' AND YRNRO Like '{2}%' AND LY Like '{3}%'", NameSearch.Text, GroupSearch.Text, IDSearch.Text, BusinessIDSearch.Text);
            UpdateFilter();
            FICount.Content = DataGrid1.Items.Count;
        }
    }

更新:

此应用程序仅可在某些本地计算机上使用,因此不应存在 SQL 注入风险。但是我知道这不是最好的“编码”。

标签: c#wpf

解决方案


像这样的东西怎么样:

这个想法是依次检查每个参数并构建查询字符串。另请注意,您不应盲目地将用户输入的文本传递给数据库——您需要防范 SQL 注入。

    string qry = null;

    if (!string.IsNullOrEmpty(BusinessIDSearch.Text))
    {
        qry = string.Format("LY Like '{0}%'", DeInjectText(BusinessIDSearch.Text));
    }
    if (!string.IsNullOrEmpty(NameSearch.Text))
    {
        if (!string.IsNullOrEmpty(qry))
            qry += " AND ";
        qry += string.Format("HAKUNIMI Like '%{0}%'", DeInjectText(NameSearch.Text));
    }
    if (!string.IsNullOrEmpty(GroupSearch.Text))
    {
        if (!string.IsNullOrEmpty(qry))
            qry += " AND ";
        qry += string.Format("KONSERNI Like '%{0}%'", DeInjectText(GroupSearch.Text));
    }
    ....
    if (!string.IsNullOrEmpty(qry))
    {
        UpdateFilter();
        FICount.Content = DataGrid1.Items.Count;
    }

public string DeInjectText(text)
{
    // Do stuff here to remove SQL injection danger from text
    return text;
}

推荐阅读