The C# program below illustrates the error described in this article.
// C# program to illustrate unexpected behavior in DataView.RowFilter
using System;
using System.Data;
namespace dvTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
DataSet myds = new DataSet();
// Create the tables
DataTable tblLegislators = new DataTable("Legislators");
tblLegislators.Columns.Add("LegislatorCode");
tblLegislators.Columns.Add("DisplayName");
DataTable tblAuthors = new DataTable("Authors");
tblAuthors.Columns.Add("BillNumber");
tblAuthors.Columns.Add("LegislatorCode");
// AuthorType: P = Primary author, C = Coauthor
tblAuthors.Columns.Add("AuthorType");
// Add tables to dataset
myds.Tables.Add(tblLegislators);
myds.Tables.Add(tblAuthors);
// Add a relationship.
myds.Relations.Add(tblLegislators.Columns["LegislatorCode"],
tblAuthors.Columns["LegislatorCode"]);
// populate the legislators table
tblLegislators.Rows.Add(new object[] {"A0123", "Smith (A0123)"});
tblLegislators.Rows.Add(new object[] {"A1234", "Jones (A1234)"});
tblLegislators.Rows.Add(new object[] {"A5038", "Jackson (A5038)"});
tblLegislators.Rows.Add(new object[] {"A0191", "Morton (A0191)"});
// Populate the Authors table.
// LegislatorCode must be present in Legislators table
tblAuthors.Rows.Add(new object[] {"001", "A0123", "P"});
tblAuthors.Rows.Add(new object[] {"001", "A5038", "C"});
// Accept changes on the dataset.
myds.AcceptChanges();
// dvLegislators is a dataview that contains legislators
// that do not have a record in tblAuthors.
DataView dvLegislators = new DataView(
tblLegislators,
"Count(Child.LegislatorCode)=0",
"DisplayName",
DataViewRowState.CurrentRows);
// Show contents
ShowLegislators(dvLegislators);
// Add another coauthor
Console.WriteLine("Add Legislator 0191 as a coauthor");
tblAuthors.Rows.Add(new object[] {"001", "A0191", "C"});
// Show contents -- why is 0191 still in this DataView?
ShowLegislators(dvLegislators);
// Re-filter the DataView
dvLegislators.RowFilter = "";
try
{
// Why does this throw an exception?
dvLegislators.RowFilter = "Count(Child.LegislatorCode)=0";
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static void ShowLegislators(DataView dvLegislators)
{
// Display contents of dvLegislators
Console.WriteLine("dvLegislators contains:");
foreach (DataRowView drv in dvLegislators)
{
Console.WriteLine(drv["DisplayName"].ToString());
}
Console.WriteLine();
}
}
}