筛选DataGridView Winforms [英] Filtering DataGridView Winforms

查看:67
本文介绍了筛选DataGridView Winforms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个接受2个用户输入的按钮,然后根据这两个输入过滤datagridview。我正在使用winforms和Sql。这是我找到并尝试实现的一些代码,但未使用过滤后的数据填充datagridview。

I am attempting to create a button which takes 2 user inputs and then filters the datagridview depending on the two inputs. I am using winforms and Sql. Here is some code I found and tried implementing but it doesn't populate the datagridview with the filtered data.

        private void button3_Click(object sender, EventArgs e) {
        dataSet31.Personal_Details.Clear();
        using (SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter(sqlCommand2.CommandText = "select * from Personal_Details WHERE '" + comboBox2 + "' LIKE '" + textBox1 + "'",
    "Data Source=Z46308;Initial Catalog=VSTest;Integrated Security=True"))
        {
            using (DataTable dataTable = new DataTable())
            {
                sqlDataAdapter.Fill(dataTable);
                this.DataGridView01.DataSource = dataTable;
            }
        }
    }


推荐答案

如果以表单加载方式加载数据,则无需运行查询来筛选网格,只需使用 DataView 来筛选数据表

If you load data in form load, then you don't need to run a query to filter grid, you can simply use a DataView to filter the data table.

在下面的示例中,我假设您使用comboBox2选择要基于其进行过滤的列名。

In the below sample I suppose that you use comboBox2 to select the column name that you want to filter based on.

//Create a data table to store data when you load them in form load
private DataTable dataTable;
private void Form1_Load(object sender, EventArgs e)
{
    dataTable = new DataTable();
    string constring = @"Data Source=Z46308;Initial Catalog=VSTest;Integrated Security=True";
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter("select * from Personal_Details", con))
        {
            //Fill the data table here
            sda.Fill(dataTable);
        }
    }
    //Set the data source of grid
    this.DataGridView01.DataSource = new DataView(dataTable);
}
private void button3_Click(object sender, EventArgs e)
{
    //Get the datasource from grid
    var dv = (DataView)this.DataGridView01.DataSource;

    //comboBox2.SelectedItem or comboBox2.SelectedValue based on your settings
    //Apply filter to data source
    dv.RowFilter = string.Format("{0} Like '%{1}%'",comboBox2.SelectedItem,   textBox1.Text);
}

编辑

您还可以使用 this.DataGridView01.DataSource = dataTable; 设置数据源,然后在过滤时只需使用 dataTable .DefaultView.RowFilter = ....

You can also use this.DataGridView01.DataSource = dataTable; to set data source, and then when filtering simply use dataTable.DefaultView.RowFilter = ....

这篇关于筛选DataGridView Winforms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆