解决了。代码已被编辑以反映解决方案。
鉴于以下情况GridView
:
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" DataKeyNames="UniqueID"
OnSelectedIndexChanging="GridView1_SelectedIndexChanging" >
<Columns>
<asp:BoundField HeaderText="Remarks" DataField="Remarks" />
<asp:TemplateField HeaderText="Listing">
<ItemTemplate>
<%# ShowListingTitle( Container.DataItem ) %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Amount" DataField="Amount" DataFormatString="{0:C}" />
</Columns>
</asp:GridView>
它指的是以下代码隐藏方法:
protected String ShowListingTitle( object /* was DataRow */ row )
{
Listing listing = ( Listing ) row;
return NicelyFormattedString( listing.field1, listing.field2, ... );
}
从DataRow
toListing
的转换失败(无法从DataRow
to转换Listing
)我确定问题出在我从 ItemTemplate 中传递的内容上,这根本不是对我从 LINQ 到 SQL 数据集的当前记录的正确引用'已经创建,它看起来像这样:
private void PopulateGrid()
{
using ( MyDataContext context = new MyDataContext() )
{
IQueryable < Listing > listings = from l in context.Listings where l.AccountID == myAccountID select l;
GridView1.DataSource = listings;
GridView1.DataBind();
}
}