Well, today it infuriated me. Therefore, I have the following markup:
<asp:ListView ID="lvComments" DataKeyNames="Id, Sender, Likes" runat="server"> <EmptyDataTemplate>
etc...
Let's say I add a label as such: <asp:Label ID="foo" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
This returns the correct DataKey identifier. Now in CodeBehind I am doing the following:
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"]; }
However, I return an “86” integer that nowhere exists as an “Id” coming from a DataSource (shown below). This ListView is nested in another ListView, and I use the same technique for my parent to get the DataKey, and it works ... I've also done this many times. I cannot understand why this does not return the correct Id number.
If this helps, here is how I fill in my data:
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(); ...
Everything nested in UpdatePanel with specific triggers. If you need more information or anything else, let me know below.