How can the DataView object reference not be set?
- by dboarman-FissureStudios
I have the following sample where the SourceData class would represent a DataView resulting from an Sql query:
class MainClass
{
private static SourceData Source;
private static DataView View;
private static DataView Destination;
public static void Main (string[] args)
{
Source = new SourceData();
View = new DataView(Source.Table);
Destination = new DataView();
Source.AddRowData("Table1", 100);
Source.AddRowData("Table2", 1500);
Source.AddRowData("Table3", 1300324);
Source.AddRowData("Table4", 1122494);
Source.AddRowData("Table5", 132545);
Console.WriteLine(String.Format("Data View Records: {0}", View.Count));
foreach(DataRowView drvRow in View)
{
Console.WriteLine(String.Format("Source {0} has {1} records.", drvRow["table"], drvRow["records"]));
DataRowView newRow = Destination.AddNew();
newRow["table"] = drvRow["table"];
newRow["records"] = drvRow["records"];
}
Console.WriteLine();
Console.WriteLine(String.Format("Destination View Records: {0}", Destination.Count));
foreach(DataRowView drvRow in Destination)
{
Console.WriteLine(String.Format("Destination {0} has {1} records.", drvRow["table"], drvRow["records"]));
}
}
}
class SourceData
{
public DataTable Table
{
get{return dataTable;}
}
private DataTable dataTable;
public SourceData()
{
dataTable = new DataTable("TestTable");
dataTable.Columns.Add("table", typeof(string));
dataTable.Columns.Add("records", typeof(int));
}
public void AddRowData(string tableName, int tableRows)
{
dataTable.Rows.Add(tableName, tableRows);
}
}
My output is:
Data View Records: 5
Source Table1 has 100 records.
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at System.Data.DataView.AddNew () [0x0003e] in /usr/src/packages/BUILD/mono-2.4.2.3
/mcs/class/System.Data/System.Data/DataView.cs:344 at DataViewTest.MainClass.Main (System.String[] args) [0x000e8] in /home/david/Projects/DataViewTest/SourceData.cs:29
I did some reading here: DataView:AddNew Method...
...and it would appear that I am doing this the right way. How come I am getting the Object reference not set?