2017-03-16 28 views
0

這裏是一個函數,將值設置爲自定義對象從DBresultset,然後我想再次返回datatable如何將對象映射到數據錶行以便在datagrid中顯示?

public DataTable getProductsTable(DataSet productData) 
{ 
    DataTable dt = new DataTable(); 
    try 
    { 
     int i = 0; 
     dt.Columns.Add("catid", typeof(string)); 

     for (i = 0; i <= productData.Tables[0].Rows.Count - 1; i++) 
     { 

      productData dataObj = new productData(); 
      dataObj.id = (string)productData.Tables[0].Rows[i]["id"].ToString(); 
      dataObj.barcode = (string)productData.Tables[0].Rows[i]["barcode"].ToString(); 
      dataObj.catid = (string)productData.Tables[0].Rows[i]["catid"].ToString(); 
      dataObj.entity_id = (string)productData.Tables[0].Rows[i]["entity_id"].ToString(); 
      dataObj.sku = (string)productData.Tables[0].Rows[i]["sku"].ToString(); 
      dataObj.name = (string)productData.Tables[0].Rows[i]["name"].ToString(); 
      dataObj.price = (string)productData.Tables[0].Rows[i]["price"].ToString(); 
      dataObj.final_price = (string)productData.Tables[0].Rows[i]["final_price"].ToString(); 
      dataObj.qty = (string)productData.Tables[0].Rows[i]["qty"].ToString(); 
      dataObj.is_in_stock = (string)productData.Tables[0].Rows[i]["is_in_stock"].ToString(); 
      dataObj.special_from_date = (string)productData.Tables[0].Rows[i]["special_from_date"].ToString(); 
      dataObj.special_to_date = (string)productData.Tables[0].Rows[i]["special_to_date"].ToString(); 
      dataObj.status = (string)productData.Tables[0].Rows[i]["status"].ToString(); 
      dataObj.parent_id = (string)productData.Tables[0].Rows[i]["parent_id"].ToString(); 
      dataObj.type_id = (string)productData.Tables[0].Rows[i]["type_id"].ToString(); 
      //data.Add(dataObj); 
      dt.Rows.Add(dataObj); 
     } 

    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
    return dt; 
} 

但它不工作,當我上面的函數運行,將顯示所有columns,但沒有價值不顯示所有rows,第一欄只顯示namespace.productData。任何人如何解決這個問題?

https://s27.postimg.org/li3lmr99f/test.png

+1

所以輸入法是一個DataSet和預期輸出是一個表,你也沒有做用'dataObj'事情又何嘗不是一種簡單的迴歸是這樣的:'返回productData.Tables [0];' –

+0

我可能稍後在productData對象 – hkguile

+0

中做些什麼。你會得到一個名爲'productData'的DataSet,並且你有一個名爲'productData'的類?那會給你很多問題。另外,檢查數據集中是否真的有數據 – Pikoh

回答

1

dt只有一列("catid")。爲每個屬性添加更多的列象下面這樣:

DataTable dt = new DataTable() 
{ 
    Columns = { "id", "barcode", "catid", etc...} 
}; 

DataTable.Rows是具有2個重載Add方法的DataRowCollection類型:

1. public void Add(DataRow row) 
2. public DataRow Add(params object[] values) 

dt.Rows.Add(dataObj);使用第二過載和在第一列中增加了一個單一的值。要添加值的正確使用

dt.Rows.Add(dataObj.id, dataObj.barcode, etc...); 
+0

謝謝,這解決了我的問題 – hkguile