use*_*620 4 .net c# asp.net listview
好吧,这让我今天疯了.所以我有以下标记:
<asp:ListView ID="lvComments" DataKeyNames="Id, Sender, Likes" runat="server">
<EmptyDataTemplate>
Run Code Online (Sandbox Code Playgroud)
等等...
假设我添加了一个标签:
<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"];
}
Run Code Online (Sandbox Code Playgroud)
但是,我返回'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();
...
Run Code Online (Sandbox Code Playgroud)
所有内容都嵌套在具有特定触发器的UpdatePanel中.如果您需要更多详细信息或任何内容,请在下面告诉我们.
试试这个:
int i = (int)lvComments.DataKeys[CommentItem.DisplayIndex]["Id"];
Run Code Online (Sandbox Code Playgroud)
编辑
我想知道它是否与您正在使用的事实有关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"];
}
Run Code Online (Sandbox Code Playgroud)