Reputation: 709
I am trying to understand how bindings work in winforms. I have the following sample code behind in which I am just trying to keep a DataGridView
up to date with a DataView
and not have to reset the DataGridView
's DataSource every time the view changes:
DataView myView = new DataView();
DataTable myTable = new DataTable();
public Form1()
{
InitializeComponent();
myTable.Columns.Add("MyColumn");
//Just make some test data.
for (int i = 0; i < 3; i++)
{
DataRow myRow = myTable.NewRow();
myRow["MyColumn"] = "TEST";
myTable.Rows.Add(myRow);
}
//Make a row that is different to filter on.
DataRow myUnRow = myTable.NewRow();
myUnRow["MyColumn"] = "TEST2";
myTable.Rows.Add(myUnRow);
myView = myTable.AsDataView();
bindingSource1.DataSource = myView;
dataGridView1.DataSource = bindingSource1.DataSource;
}
private void button1_Click(object sender, EventArgs e)
{
//Refilter the view.
myView = (from dataRow in myTable.AsEnumerable()
where (string)dataRow["MyColumn"] == "TEST2" select dataRow).AsDataView();
//When this code finishes datagridview1 still shows all the original rows. Should just show the one row with "TEST2"?
}
I have previously used a BindingList
and bound that to a comboBox
's datasource and changes were automatically changed when the list did. I am trying to get this same sort of interaction.
Upvotes: 2
Views: 1032
Reputation: 19386
Even if you bind to a DataTable, there is a default view DataView
. So, really, you always get the DataView
. Data view allows you for sorting and other tricks with data, which remains in same order in your data source. This is all to it, really. You can prepare multiple data views and by switching them you can change the way data look in the grid.
Upvotes: 2