ListView DataKeys [Index]返回随机DataKeyName“Id”数

时间:2011-11-10 23:26:57

标签: c# asp.net .net listview

好的,这让我今天疯了。 所以我有以下标记:

<asp:ListView ID="lvComments" DataKeyNames="Id, Sender, Likes" runat="server">
<EmptyDataTemplate>

等...

假设我添加了一个标签: <asp:Label ID="foo" Text='<%# Eval("Id") %>' runat="server"></asp:Label>

返回正确的DataKey“Id”。现在在CodeBehind中我正在执行以下操作:

 protected void CommentUp_Click(object sender, EventArgs e)
 {
     LinkButton CommentUp = (LinkButton)sender;
     ListViewItem CommentItem = CommentUp.NamingContainer as ListViewItem;
     ListView lvComments = (ListView)CommentItem.NamingContainer;

     int i = (Int32)lvComments.DataKeys[CommentItem.DisplayIndex].Values["Id"];
 }

但是,我返回'86'一个整数,它不存在于来自DataSource的“Id”(如下所示)。这个ListView嵌套在另一个ListView中,我在其父级上使用相同的技术来获取DataKey并且它正在工作......我也做了很多次。我无法弄清楚为什么这不会返回正确的Id整数。

如果有帮助,这就是我填充数据的方式:

public static List<Comment> GetAll(Int32 StreamId)
{
    const string sqlString =
        "SELECT * FROM Comments WHERE StreamId = @StreamId;";

    List<Comment> list = new List<Comment>();
    SqlConnection sqlConnection = taaraf.GetConn();
    using (SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection))
    {
        sqlCommand.Parameters.AddWithValue("@StreamId", StreamId);

        sqlConnection.Open();
        SqlDataReader sqlReader = sqlCommand.ExecuteReader();
        while (sqlReader.Read())
        {
            Comment objComment = new Comment 
            {
                Id = (Int32)sqlReader.GetValue(0),
                Value = sqlReader.GetValue(1).ToString(),
                Sender = sqlReader.GetValue(2).ToString(),
                IsRead = taaraf.IntToBool((Int32)sqlReader["IsRead"]),
                StreamId = (Int32)sqlReader.GetValue(5) 
            };
            list.Add(objComment);
        }
        sqlConnection.Close();
        sqlConnection.Dispose();
    }
    return list;
}

...
lvComments.DataSource = Comment.GetAll(StreamId);
lvComments.DataBind();
...

所有内容都嵌套在具有特定触发器的UpdatePanel中。如果您需要更多详细信息或任何内容,请在下面告诉我们。

2 个答案:

答案 0 :(得分:5)

请改为尝试:

int i = (int)lvComments.DataKeys[CommentItem.DisplayIndex]["Id"];

修改

我想知道它是否与您使用DisplayIndex的事实有关。请尝试改为使用DataItemIndex

//double check and make sure that this is getting the correct item
ListViewItem commentItem = ((LinkButton)sender).NamingContainer as ListViewItem;

if (commentItem != null)
{
    //instead of using the DisplayIndex use the DataItemIndex
    int id = (int)lvComments.DataKeys[commentItem.DataItemIndex]["Id"];
}

答案 1 :(得分:0)

如果是enter code here radcontrols,

itemdatabound方法中:

if (   e.Item.ItemType ==    RadListViewItemType.DataItem)
{
    RadListViewDataItem    `item `=    (RadListViewDataItem)e.Item;` 
    //here we read the DataKeys values from the item

    String EmpID = lstCompContctPerson.DataKeyValues[item.DataItemIndex]["CompanyContactPersonID"].ToString();`enter code here`
    hdnCompanyID.Value = EmpID;
}