gpt4 book ai didi

c# - 如何在具有两个文本框的 dataGridView 中进行多重过滤?

转载 作者:行者123 更新时间:2023-11-29 11:41:17 26 4
gpt4 key购买 nike

例如,当名字相同但姓氏不同时过滤姓名并写入姓氏过滤器,但保留名称过滤器。

带有文本框的示例:

连接:

public void read_data(string query, ref DataSet principal, string tabla)
{
try
{
string cadena = "Server=0.0.0.0; Database=DB; Uid=user; Pwd=pass";
MySqlConnection cn = new MySqlConnection(cadena);
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(principal, tabla);
cn.Close();
}
catch (Exception ex)
{

}
}

加载dataGridView:

private void Form1_Load(object sender, EventArgs e)
{
this.read_data("Select * From reg", ref result, "reg");
this.filtro = ((DataTable)result.Tables["regi"]).DefaultView;
this.dataGridView1.DataSource = filtro;
}

事件:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
string data_output = " ";
string[] search_word = this.textBox1.Text.Split(' ');

foreach (string word in search_word)
{
if (data_output.Length == 0)
{
data_output = "(FirstName LIKE '%" + word + "%')";
}
else
{
data_output += "(FirstName LIKE '%" + word + "%')";
}
}
this.filtro.RowFilter = data_output;
}

最佳答案

这是实现您的要求的一种方法。

创建一个通用函数以从两个文本框调用,如下所示

    private string GetFilterExpression(string sFilterExprValue, string sFilterFieldName)
{
string sFilterExpr = "";
string[] search_word = sFilterExprValue.Split(' ');

foreach (string word in search_word)
{
if (sFilterExpr.Length == 0)
{
sFilterExpr = "(" + sFilterFieldName + " LIKE '%" + word + "%')";
}
else
{
sFilterExpr += " AND (" + sFilterFieldName + " LIKE '%" + word + "%')";
}
}

return sFilterExpr;
}

从两个文本框的按键事件中调用通用函数,如下所示;

带有名字过滤器的文本框 1

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
// Text box to enter Firstname filter
string sFilter = GetFilterExpression(this.textBox1.text, "FirstName");

if (!this.textBox2.text)
{
string sLastNameFilter = GetFilterExpression(this.textBox2.text, "LastName");

if (!String.IsNullOrEmpty(sLastNameFilter)) // Concat the Last Name Filter
sFilter += String.IsNullOrEmpty(sFilter) ? "" : " AND " + sLastNameFilter;
}

this.filtro.RowFilter = sFilter;
}

带有姓氏过滤器的文本框 2

    private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
// Text box to enter Lastname filter
// Assume the field storing last name is 'Lastname'
string sFilter = GetFilterExpression(this.textBox2.text, "LastName");

if (!this.textBox1.text)
{
string sFirstNameFilter = GetFilterExpression(this.textBox1.text, "FirstName");

if (!String.IsNullOrEmpty(sFirstNameFilter))
sFilter += String.IsNullOrEmpty(sFilter) ? "" : " AND " + sFirstNameFilter;
}

this.filtro.RowFilter = sFilter;
}

希望这对您有所帮助,如果这解决了您的问题,请将其标记为这样。

已编辑:更新textBox2_Keyup事件以连接输入到textBox1中的任何过滤器表达式

关于c# - 如何在具有两个文本框的 dataGridView 中进行多重过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com