Design advise needed on editing and filtering a datagridview

后端 未结 2 1698
离开以前
离开以前 2021-01-17 07:07

I have a design question that involves DataGridView and DataTable, bound by a BindingSource in a WinForms application. The DataTable is populated by a sql server table.

2条回答
  •  太阳男子
    2021-01-17 07:25

    The filter shouldn't affect the loop. For example, in the following code I set the DataGridView.DataSource from a DataTable that has an applied filter and loop through the table, printing values:

    DataTable dt = new DataTable();
    
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    
    dt.Rows.Add("Foo", 1);
    dt.Rows.Add("Bar", 2);
    dt.Rows.Add("Baz", 3);
    
    string filterField = "Name";
    string filterText = "B";
    dt.DefaultView.RowFilter = string.Format("[{0}] LIKE '%{1}%'", filterField, filterText);
    
    this.dataGridView1.DataSource = dt;
    
    foreach (DataRow row in dt.Rows)
    {
        Console.WriteLine("{0}", row.ItemArray[0]);
    }
    

    With the filter, the DataGridView displays only select entries. But looping through the DataTable rows still prints every entry.

    Therefore, when handling binding such as a BindingSource, after the DataGridView is already sourced, you might change your filter like so to have a dynamic searching option:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = this.dataGridView1.DataSource as BindingSource;
        DataTable dt = bs.DataSource as DataTable;
        dt.DefaultView.RowFilter = string.Format("[{0}] LIKE '{1}%'", "Name", this.textBox1.Text);
    }
    

提交回复
热议问题