c# - ListView DataKeys[Index] 返回随机 DataKeyName "Id"数字

标签 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 中。如果您需要更多详细信息或任何内容,请在下方告诉我。

最佳答案

试试这个:

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"];
}

关于c# - ListView DataKeys[Index] 返回随机 DataKeyName "Id"数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087855/

相关文章:

C#,实现子类定义的具体变量的抽象父类(super class)?

javascript - 来自 JSON 数据的饼图

c# - Ajax 计时器在处理另一个请求时不轮询

c# - 如何获取网址的内容类型?

c# - 制作引用本身的副本?

c# - 如何将 JSON 字符串绑定(bind)到真实对象定义?

c# - 通过 C# Web 浏览器抓取网站以获取元素名称和 ID

c# - 如何通过动态创建客户端代理来使用 WCF 服务

javascript - 使用 javascript 更改按钮的文本,但单击时,服务器端接收到的按钮文本仍保持不变

c# - 如何访问另一个程序集的 .resx?