Design advise needed on editing and filtering a datagridview

后端 未结 2 1696
离开以前
离开以前 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);
    }
    
    0 讨论(0)
  • 2021-01-17 07:34

    I just found an even better way to filter the DataGridViewfrom a question (yes it was a question) posted by mj82:

    Filtering DataGridView without changing datasource

    This was the most helpful part of the question.

    DataTable dt = new DataTable();
    BindingSource bs = new BindingSource();
    
    private void Form1_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("id", typeof(int));
        dt.Columns.Add("country", typeof(string));
    
        dt.Rows.Add(new object[] { 1, "Belgium" });
        dt.Rows.Add(new object[] { 2, "France" });
        dt.Rows.Add(new object[] { 3, "Germany" });
        dt.Rows.Add(new object[] { 4, "Spain" });
        dt.Rows.Add(new object[] { 5, "Swiss" });
        dt.Rows.Add(new object[] { 6, "United Kingdom" });
    
        bs.DataSource = dt;
        dataGridView1.DataSource = bs;
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        MessageBox.Show("DataSource type BEFORE = " + dataGridView1.DataSource.GetType().ToString());
    
        bs.Filter = string.Format("country LIKE '%{0}%'", textBox1.Text);
    
        MessageBox.Show("DataSource type AFTER = " + dataGridView1.DataSource.GetType().ToString());
    }
    
    0 讨论(0)
提交回复
热议问题