我有以下示例,其中SourceData
類將是從SQL查詢得到的數據視圖:如何設置DataView對象引用?
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);
}
}
我的輸出是:
數據查看記錄:5
源表1有100條記錄。未處理的異常信息:System.NullReferenceException:在System.Data.DataView.AddNew()[0x0003e]在/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]在/home/david/Projects/DataViewTest/SourceData.cs:29
我做了一些閱讀這裏:DataView:AddNew Method...
......和這樣看來,我這個做正確的方式。我如何得到沒有設置的對象引用?
你的實際目標是什麼?你想要在DataGridView上顯示數據嗎? DataView通常用作DataSource容器。它不是一個顯示數據的GUI對象。 – galford13x 2010-05-27 03:16:10
請記住,這是一個測試,以解決dataview無法正常工作的問題。最後,是的,目標數據視圖將顯示在數據網格中。 – IAbstract 2010-05-27 03:21:45