根据任何文本框中的任何更改更新筛选器和DataGrid



我有4个文本框。我使用它们中的每一个作为DataGrid的过滤参数。问题是,我必须用IF函数覆盖所有可能的变体,以便使它们正确工作。有更好的方法吗?

以下是一个甚至没有涵盖所有变体的示例。我还需要分别为每个文本框修改它。

这是代码:

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注入风险。然而,我知道这不是最好的";编码";。

这样的东西怎么样:

这个想法是依次检查每个参数并构建查询字符串。还要注意,您不应该盲目地将用户输入的文本传递给数据库——您需要防止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;
}

最新更新