2012-12-27 50 views
2

爲什麼我得到一個「有位置0處沒有任何行」例外:將數據添加到類型化數據集編程

DSGeneral dg = new DSGeneral(); 

// I create 1 table 
DSGeneral.GeneralDataTable t = new DSGeneral.GeneralDataTable(); 
dg.Tables.Add(t); 

// The 1st row 
DSGeneral.GeneralRow r = t.NewGeneralRow(); 
r.Code = "code"; 
r.Value = "7"; 
t.Rows.Add(r); 

// The 2nd row 
DSGeneral.GeneralRow r2 = t.NewGeneralRow(); 
r2.Code = "exp"; 
r2.Value = "5"; 
t.Rows.Add(r2); 

它拋出這裏:

int numClave = Convert.ToInt16(dg.General[0].Value); 

此外,調試,我可以看到我的鍵入數據集dg有2個表,我想知道爲什麼。

回答

5

當您使用strongly typed DataSets時,您將在設計器上聲明表和數據適配器。 DataTables然後已經是DataSets的一部分,因此您不需要再將它們添加到它。

這解釋了爲什麼數據集包含兩個表而不是一個表。由於同樣的原因,你會得到例外。您已將行添加到手動創建的表格中,而不是添加到聲明中。

dg.General[0].Rows[0].Value 

訪問自動生成DataTable這仍然是空的。

所以,你只需要使用現有的表:

DSGeneral dg = new DSGeneral(); 
DSGeneral.GeneralRow r = dg.General.NewGeneralRow(); 
r.Code = "code"; 
r.Value = "7"; 
dg.General.AddGeneralRow(r); 
+0

我編輯的代碼是不帶'添加()'兩個表和行,但現在它說有一個沒有行,當我做'DG .General.Rows.Count' – anmarti

+1

@a_maar:是的,當然你還需要將行添加到'DataTable'中。只有表格存在,而不是行。 –

+0

@a_maar:編輯我的答案以澄清這一點。必須有一個自動生成的方法'AddGeneralRow',您可以使用它來添加強類型的'DataRow'。 –