How To Add New Rows to a Filtered DataView

How To Add New Rows to a Filtered DataView

Suppose you have a “view” into a set of records. One column of the data contains a country ID, (such as “US”):

 DataView myDataView = new DataView(myTable); myDataView.RowFilter = "country = 'us'"; myGrid.DataSource = myDataView; 

If you filter the records so that only the “US” records show up in your view, and then add a new record, the new record won’t show up?because it’s filtered out.

DataRowView drv = myDataView.AddNew(); 

To solve this problem, you might spend considerable effort debugging. Or maybe your immediate reaction would be to victimize the datagrid (which could possibly be the third-party component). But the reality is that the problem is with the code! Take a look:

myDataView.RowFilter = "country = 'us'", 

Due to this filter, dataview would have only those rows which satisfy the condition that all other rows are not part of the view. So when a new row is added, the value of drRow[“country”] is DBNull due to the fact that the new row is not part of filtered dataview.

Here’s the solution to this problem:

 // Change values in the DataRow. drRow = drv.Row[0]; drRow ["country"]='us' drRow.EndEdit(); 

Now the new row will be visible in the grid.

Note: If your filter expression has multiple columns, all the columns must be set explicitly in the new row so that the filter condition is satisfied.


Share the Post: