想知道用我的對象數據填充GridView的最佳方式。使用對象數據填充GridView
我不得不從一個複雜的對象Sale
,其結構是這樣的顯示產品列表:
class Sale {
int id;
List<SaleItem> saleItems;
}
class SaleItem {
int id;
int quantity;
Product product;
BillingAddress billingAddress;
ShippingAddress shippingAddress;
}
class Product {
int id;
string name;
List<BuyingConfiguration> buyingConfigurations;
}
class BuyingConfiguration {
string name; // like size, color, material
string value;
}
和我的格子應該是這樣的:
Sale Items
+---------+---+------------+------------+----------------+
| Name | # | B. Address | S. Address | Configurations |
+---------+---+------------+------------+----------------+
| Ferrari | 2 | -- | -- | Color: red |
| | | | | Engine: Xyz |
+---------+---+------------+------------+----------------+
| Jax | 1 | -- | -- | Color: blue |
| | | | | Engine: Abc |
+---------+---+------------+------------+----------------+
我應該實現一個ObjectDataSource爲我的Sale
對象?有沒有更好的解決方案?
編輯2:讓我試着讓自己清楚:問題不在於如何顯示配置。 我的問題是,Sale
對象從持久層返回到我的代碼,這就是爲什麼我不希望GridView直接訪問數據庫。相反,它需要從我的Sale
對象中加載其所有數據,如何實現?
編輯:
網格的要求標記:
<asp:GridView runat="server" ID="GridProdutos" OnRowDataBound="GridProdutos_OnRowDataBound"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Name" />
<asp:BoundField HeaderText="#" />
<asp:BoundField HeaderText="B. Address" />
<asp:BoundField HeaderText="S. Address" />
<asp:BoundField HeaderText="Configurations" />
</Columns>
</asp:GridView>
醜陋的解決方案,到目前爲止,使用OnRowDataBound(我想避免這一點!):
protected void GridProdutos_OnRowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.DataItem == null)
return;
SaleItem item = (SaleItem)e.Row.DataItem;
e.Row.Cells[0].Text = item.product.name;
e.Row.Cells[1].Text = item.quantity.ToString();
StringBuilder sbConfigurations = new StringBuilder();
foreach (BuyingConfiguration configurationItem in item.product.buyingConfigurations) {
sbConfigurations.AppendFormat("{0}: {1}<br />", configurationItem.name, configurationItem.value);
}
e.Row.Cells[4].Text = sbConfigurations .ToString();
}
請使用網格定義顯示您的頁面標記。 –
@DavidePiras它很簡單,添加到問題 –
我想你可以添加一箇中繼控件來顯示配置項。中繼器的數據源應該通過使用給定數據源的「綁定()」方法來綁定,這消除了RowDataBound的東西。希望這可以幫助!! – Praveen