c#如何过滤Datagridview绑定到数据集 - Accent Insentitive

时间:2016-10-27 22:08:36

标签: c# datagridview filter dataset accent-insensitive

我有一个DataGridView绑定到DataSet,某个值(名称)有重音(例如:é,í,ž,ć,é,á),我会执行过滤重音不敏感的。

通常我会像这样过滤DataGridView

private void textBox1_TextChanged(object sender, EventArgs e)
{
    MyDataSet.People.DefaultView.RowFilter = "Name LIKE '%" + textBox1.Text + "%'";
    dataGridView1.DataSource = MyDataSet.People.DefaultView;
}

我尝试在我的数据库中更改此内容:

CREATE TABLE [dbo].[People] (
[Num]        INT           NOT NULL,
[Name]     NVARCHAR (50) NOT NULL
);

由此

CREATE TABLE [dbo].[People] (
[Num]        INT           NOT NULL,
[Name]     NVARCHAR (50) COLLATE Latin1_General_CI_AI NOT NULL
);

并试图改变:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    MyDataSet.People.DefaultView.RowFilter = "Name LIKE '%" + textBox1.Text + "%' COLLATE Latin1_General_CI_AI";
    dataGridView1.DataSource = MyDataSet.People.DefaultView;
}

但它不起作用。

1 个答案:

答案 0 :(得分:0)

我可以提出以下决定。

添加到名为NameWithoutAccent的数据表新列。

MyDataSet.People.Columns.Add("NameWithoutAccent", typeof(string));

使用已删除重音的值填充此列。此列将进行过滤。

foreach (DataRow row in MyDataSet.People.Rows)
{
    string name = (string)row["Name"];
    string nameWithoutAccent = RemoveAccent(name);
    row["NameWithoutAccent"] = nameWithoutAccent;
}

首先使用String.Normalize方法对字符串进行规范化以删除重音符。然后用正则表达式删除所有变音符号。 MUnicode category“所有变音符号”。

public string RemoveAccent(string name)
{
    string normalizedName = name.Normalize(NormalizationForm.FormD);
    string pattern = @"\p{M}";
    string nameWithoutAccent = Regex.Replace(normalizedName, pattern, "");
    return nameWithoutAccent;
}

数据绑定后隐藏此列。

dataGridView1.Columns["NameWithoutAccent"].Visible = false;

也会从重音清除输入过滤器。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    string nameWithoutAccent = RemoveAccent(textBox1.Text);
    MyDataSet.People.DefaultView.RowFilter = "NameWithoutAccent LIKE '%" + nameWithoutAccent + "%'";
}