Passing a LINQ DataRow Reference in a GridView's ItemTemplate

Posted by Bob Kaufman on Stack Overflow See other posts from Stack Overflow or by Bob Kaufman
Published on 2010-03-25T12:08:52Z Indexed on 2010/03/25 12:13 UTC
Read the original article Hit count: 443

Filed under:
|
|
|
|

Given the following 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( ( ( System.Data.DataRowView ) ( Container.DataItem ) ).Row ) %>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField HeaderText="Amount" DataField="Amount" DataFormatString="{0:C}" />
</Columns>
</asp:GridView>

which refers to the following code-behind method:

protected String ShowListingTitle( DataRow row )
{
    Listing listing = ( Listing ) row;

    return NicelyFormattedString( listing.field1, listing.field2, ... );
}

The cast from DataRow to Listing is failing (cannot convert from DataRow to Listing) I'm certain the problem lies in what I'm passing from within the ItemTemplate, which is simply not the right reference to the current record from the LINQ to SQL data set that I've created, which looks like this:

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();
    }
}

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about itemtemplate