2013-05-10 47 views
0

我已經使用MSDN的示例向我的DataSet添加新記錄。我甚至使用了相同的變量名來保持簡單。將新記錄添加到輸入的數據集錯誤

C#代碼

NorthwindDataSet.CustomersRow newCustomersRow = 
northwindDataSet1.Customers.NewCustomersRow(); 

    newCustomersRow.CustomerID = "5"; 
    newCustomersRow.CompanyName = "Alfreds Futterkiste"; 

    northwindDataSet1.Customers.Rows.Add(newCustomersRow); 

我得到的錯誤是The name 'northwindDataSet1' does not exist in the current context

我覺得這很奇怪,因爲我直接使用的代碼從MSDN。

我的DataSet被稱爲NorthwindDataSet,該表稱爲Customers。我試過northwindDataSet但仍然是一樣的錯誤。

+0

你明明沒有申報'northwindDataSet1'在你的代碼,至少不會在適當的水平。 – hattenn 2013-05-10 11:03:43

+0

在這段代碼中我沒有定義northwindDataSet1 – 2013-05-10 11:04:17

+0

(這與ASP.NET無關 - 我更改了標籤以反映它更多地使用ADO.NET。) – 2013-05-10 11:08:18

回答

4

MSDN中的代碼示例代碼片段並非設計爲完整。您需要一個名爲northwindDataSet1的變量才能使用此代碼段。

例如,你可以只使用:

NorthwindDataSet northwindDataSet1 = new NorthwindDataSet(); 

...但更可能你會想從一個數據適配器,或者一些這樣的數據庫中讀取它。

重要的是你試着真的明白正在呈現的代碼。即使你是新來的鍵入數據集,也應該清楚這是試圖使用一個現有的變量 - 這意味着爲了使用代碼,你必須這個變量。

如果您對C#有足夠的新意,並且您不理解此處使用的語法(當然,當然沒有新的錯誤),我建議您在移動之前先學習C#的基礎知識到數據庫訪問。通過這種方式,當您瞭解更高級的主題時,您將處於更好的位置。一次學習一件事比一次性學習一切都更有效率。

我的DataSet名爲NorthwindDataSet

你這是什麼意思究竟?你的意思是你的數據集類型,或者你有屬性調用NorthwindDataSet某處?基本上,某些事情需要在某個時候創建​​數據集類型的實例......目前還不清楚您有多遠。

+0

感謝您答案,儘管由於某種原因,數據不會被保存到數據庫中。 NorthwindDataSet northwindDataSet1 = new NorthwindDataSet(); NorthwindDataSet.CustomersRow newCustomersRow = northwindDataSet1.Customers.NewCustomersRow(); newCustomersRow.CustomerID =「5」; newCustomersRow。CompanyName =「Alfreds Futterkiste」; northwindDataSet1.Customers.Rows.Add(newCustomersRow); northwindDataSet1.Customers.AcceptChanges(); – 2013-05-10 11:16:42

+0

@JoshuaHornby:你認爲該代碼中的哪個部分能夠被保存?你甚至沒有指定一個數據庫來交談。我建議你退後一步,閱讀完整的* ADO.NET教程。 – 2013-05-10 11:18:17

+0

您可以將我的指向數據庫的代碼示例的正確導向器嗎? – 2013-05-10 11:22:21

0

第一定義它像

NorthwindDataSet northwindDataSet1 = new NorthwindDataSet(); 
NorthwindDataSet.CustomersRow newCustomersRow = 
northwindDataSet1.Customers.NewCustomersRow(); 

newCustomersRow.CustomerID = "5"; 
newCustomersRow.CompanyName = "Alfreds Futterkiste"; 

northwindDataSet1.Customers.Rows.Add(newCustomersRow); 
相關問題