我有一个模特
public class ItemHistory
{
public int TotalItems;
public int ScannedItems;
public int PendingItems;
}
按钮单击事件我想根据该值加载网格。 Button_Click
的代码int TotalItems = Convert.ToInt32(lblItemsScanned.Text);
int ScannedItems = Convert.ToInt32(lblItemsScanned.Text);
int PendingItems = TotalItems - ScannedItems;
List<ItemHistory> ih = new List<ItemHistory>();
ih.Add(new ItemHistory
{TotalItems, ScannedItems, PendingItems});
gvrecap.DataSource = ih;
gvrecap.DataBind();
但是,它给出了以下错误:
无法初始化类型&#39; ConsignmentCreation.ItemHistory&#39;使用集合初始值设定项,因为它没有实现&#39; System.Collections.IEnumerable&#39;
无法理解。请帮忙...提前致谢
感谢您的解决方案,但我现在面临Databind();
名称为&#39; TotalItems&#39;的字段或属性在所选数据源上找不到。
以下是Gridview安排:
<asp:GridView ID="gvrecap" runat="server"
AutoGenerateColumns="false" PagerSettings-Mode="NumericFirstLast" PageSize="25" Width="741px">
<Columns>
<asp:BoundField DataField="TotalItems" HeaderText="TotalItems" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="50" />
<asp:BoundField DataField="ScannedItems" HeaderText="ScannedItems" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="50" />
<asp:BoundField DataField="PendingItems" HeaderText="PendingItems" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="50" />
</Columns>
</asp:GridView>
答案 0 :(得分:1)
使用新的ItemHistory对象初始化列表的语法不太对。您需要指定字段名称和值。
int pendingItems = 10;
int scannedItems = 5;
int totalItems = 15;
List<ItemHistory> ih = new List<ItemHistory>();
ih.Add(new ItemHistory
{
PendingItems = pendingItems,
ScannedItems = scannedItems,
TotalItems = totalItems
});
以上作品。希望有所帮助。
答案 1 :(得分:0)
您没有正确使用对象初始值设定项。 试试这个(未经测试):
int totalItems = Convert.ToInt32(lblItemsScanned.Text);
int scannedItems = Convert.ToInt32(lblItemsScanned.Text);
int pendingItems = totalItems - scannedItems;
List<ItemHistory> ih = new List<ItemHistory>();
ih.Add(new ItemHistory
{TotalItems = totalItems, ScannedItems = scannedItems , PendingItems = pendingItems });
gvrecap.DataSource = ih;
gvrecap.DataBind();
我建议在模型中使用Properties而不是为此目的使用变量,如下所示:
public class ItemHistory
{
public int TotalItems {get;set;}
public int ScannedItems {get;set;}
public int PendingItems {get;set;}
}