好吧,这让我今天发疯了。 所以我有以下标记:
<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/