【发布时间】:2019-07-10 02:10:00
【问题描述】:
我创建了一个 DataGridView 控件来列出一些内容。但是,我想根据 textBox 中的条件将特定行放在一起(而不是将它们全部放在一行中)。
谢谢!
代码如下:
DataTable table = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
// populate dgv from datatable
// add columns
table.Columns.Add("Number", typeof(int));
table.Columns.Add("Food", typeof(string));
// add rows
table.Rows.Add(1, "BBQ");
table.Rows.Add(2, "Pear");
table.Rows.Add(3, "Eggs");
table.Rows.Add(4, "Banana");
table.Rows.Add(5, "Noodle");
table.Rows.Add(6, "Orange");
table.Rows.Add(7, "Mango");
table.Rows.Add(8, "Beef");
dataGridView1.DataSource = table;
}
private void Button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "Fruit" )
{
}
}
例如,当我在文本框中键入“水果”时。所有包含一种水果的行都会自动排列在一起,从第一行开始,如下所示:
- 梨
- 香蕉
- 橙色
- 芒果
当在文本框中输入“肉类”一词时,其余包含某种肉类的行也是如此。
【问题讨论】:
-
您需要在数据表中有另一列
FoodType,并在用户输入Fruit时根据表中的该列过滤行。 -
以上,然后是DataView.RowFilter
= $"FoodType = '{textBox1.Text}'";。不过,您可能应该预先定义可以作为查询对象的类别。使用手工制作的 DataTable,您可以使用Enum(枚举类别,使用enum.ToString()将值作为文本呈现给用户,并使用值来查询数据)。可能使用 ComboBox 而不是 TextBox 作为选择器。也许是启用了自动完成功能的 ComboBox。 -
无论如何,您的将特定行放在一起称为过滤器。
标签: c# winforms datagridview