2013-08-30 88 views
1

早上好。C#xmlAttribute.Value未將對象引用設置爲對象的實例

很快。

使用的XmlDocument我programmaticaly創建文檔,這需要看起來像這樣(樣品):

<report> 
    <header version="1" reportDate="2013-08-27" salesDate="2013-08-26"/> 
    <data> 
     <companies> 
      <company id="ABCD"> 
       <customers> 
        <customer id="100000" storeId="AA"/> 
        <customer id="100001" storeId="AB"/> 
        <customer id="100002" storeId="AC"/> 
       </customers> 
      </company> 
     </companies> 
    </data> 
</report> 

我需要從幾的DataGridView的抓取數據,所以的foreach環路正在密集使用。

我不能工作了,也沒有找到答案(總是一些關於讀取XML,沒有創建)就是爲什麼如下所示的代碼拋出我:未設置爲實例

對象引用對象

這是代碼的示例使用:

[...] 

XmlNode customersNode = doc.CreateElement("customers"); 
companyNode.AppendChild(customersNode); 

XmlNode customerNode; 
XmlAttribute customerAttribute; 

foreach (DataGridViewRow row in dgvCustomers.Rows) 
{ 
    customerNode = doc.CreateElement("customer"); 

    customerAttribute = doc.CreateAttribute("id"); 
    customerAttribute.Value = row.Cells[0].Value.ToString(); 
    // 
    // __HERE__ is the problem (or a line above) 
    // 
    customerNode.Attributes.Append(customerAttribute); 

    customerAttribute = doc.CreateAttribute("storeId"); 
    customerAttribute.Value = row.Cells[1].Value.ToString(); 
    customerNode.Attributes.Append(customerAttribute); 

    customersNode.AppendChild(customerNode); 
} 

[...and so on...] 

另外

customerNode.Attributes.Append(customerAttribute); 

下劃線(VS2010編輯器)與該尖端:

Possible 'System.NullReferenceException' 

但我認爲這是上述問題的一個原因是什麼?

任何支持表示讚賞,並非常感謝您的時間和知識共享。

此致敬禮!

+0

你確定'row.Cells [0]'有一個值(不是nul)嗎?檢查與調試 –

+0

快速row.Cells [0]。這個值,看看這是否有價值 – Rex

+0

看到我的最後一條評論。謝謝! –

回答

1

我還沒有試過運行中的代碼,但是:你可能會發現,簡化就更難得到錯誤:

XmlElement customerNode; // <==== note this is XmlElement, not XmlNode 
XmlAttribute customerAttribute; 

foreach (DataGridViewRow row in dgvCustomers.Rows) 
{ 
    customerNode = doc.CreateElement("customer"); 
    customerNode.SetAttribute("id", row.Cells[0].Value.ToString()); 
    customerNode.SetAttribute("storeId", row.Cells[1].Value.ToString()); 

    customersNode.AppendChild(customerNode); 
} 

您還可能要檢查這個問題實際上不是那row.Cells[0].Value.ToString()row.Cells[1].Value.ToString()正在拋出異常。

+0

好吧,知道了,將數據加載到DGV的方法會在最後一個包含數據的行下面添加空行。它會拋出一個異常:)添加檢查,像魅力一樣工作,謝謝大家! –

相關問題