使用 DataBinder.Eval 时,ListViewDataItem 不包含名称为 'CommentId' 的 属性

ListViewDataItem does not contain a property with the name 'CommentId' when using DataBinder.Eval

我有一个 ListView 显示用户对特定新闻文章的所有评论。

我需要每个评论的评论和作者 ID,这样我就可以在它旁边显示一个删除按钮(如果它是由相应的用户创建的)。

问题是行 DataBinder.Eval(dataItem, "CommentId") 抛出以下错误

System.Web.UI.WebControls.ListViewDataItem' does not contain a property with the name 'CommentId'.

我也尝试将 CommentId 更改为 Comments.CommentId,但没有成功。

我做错了什么? 感谢任何帮助。

谢谢!

在News.aspx

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="ListView1_ItemDataBound">

                    <ItemTemplate>
                        <span style="">
                            <table>
                                <tr>
                                    <td style="width=60px">
                                        <asp:Label Text='<%# Eval("UserName") + ":"%>' runat="server" ID="UserNameLabel" Font-Bold="true" /><br />
                                    </td>
                                    <td>
                                        <asp:Label Text='<%# Eval("body") %>' runat="server" ID="bodyLabel" /><br />

                                    </td>
                                    <td>
                                        <asp:Button ID="DeleteCommentButton" runat="server" Text="Delete" OnClick="DeleteCommentButton_Click" />
                                    </td>
                                </tr>
                            </table>
                            <br />
                        </span>
                    </ItemTemplate>

                    <LayoutTemplate>
                        <div runat="server" id="itemPlaceholderContainer" style=""><span runat="server" id="itemPlaceholder" /></div>
                        <div style="">
                        </div>
                    </LayoutTemplate>

                </asp:ListView>
                <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' SelectCommand="SELECT Comments.CommentId, Users.UserId, Comments.body, Users.UserName FROM Comments INNER JOIN Users ON Comments.UserId = Users.UserId WHERE NewsId = @NewsId">
                    <SelectParameters>
                        <asp:Parameter Name="NewsId" Type="Int32" />
                    </SelectParameters>
                </asp:SqlDataSource>

在News.aspx.cs:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;

            int commentId = (int)DataBinder.Eval(dataItem, "CommentId");
...

我是这样解决的:

ListViewDataItem dataItem = e.Item as ListViewDataItem; 
int commentId = (int)DataBinder.Eval(dataItem.DataItem, "CommentId");
Guid authorId = (Guid)DataBinder.Eval(dataItem.DataItem, "UserId");