c# - 在任何文本框中的任何更改上更新过滤器和 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 注入风险。但是我知道这不是最好的“编码”。
解决方案
像这样的东西怎么样:
这个想法是依次检查每个参数并构建查询字符串。另请注意,您不应盲目地将用户输入的文本传递给数据库——您需要防范 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;
}
推荐阅读
- javascript - highcharts 多列图表不显示
- sql-server - 如何使用 MSSQL 查询更改数据类型
- python - 卷积模糊图像 - python
- onedrive - 登录到 Sharepoint Online 失败
- c# - 在 .net core 项目中按环境加载 WCF 服务
- acumos - 在 acumos 中以管理员身份登录
- sql - 基于可变长度字段将一列一分为二
- error-handling - Nano:dyld:未加载库:/usr/local/opt/gettext/lib/libintl.8.dylib
- excel - 具有重叠时间范围的时间序列,仅使用 Excel Power Query 中的最新
- git - 是否可以在旧代码 Visual Studio 2003 环境中使用 bitbucket?