Design advise needed on editing and filtering a datagridview

后端 未结 2 1695
离开以前
离开以前 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: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());
    }
    

提交回复
热议问题