I am doing my school assignment on a web chat application. I wish use a datalist to show the previous chat in a chatbox, but the datalist do not show up.
This is my code in .aspx:
<asp:DataList ID="DataList3" runat="server">
<ItemTemplate runat="server">
<div class="lv-item media">
<div class="lv-avatar pull-left">
<asp:Image ID="Image4" runat="server" ImageUrl='<%# Bind("Image") %>' />
</div>
<div class="media-body">
<div class="ms-item">
<span class="glyphicon glyphicon-triangle-left" style="color: #000000;"></span>
<asp:Label ID="Message" runat="server" Text='<%# Bind("Message") %>'></asp:Label>
</div>
<small class="ms-date"><span class="glyphicon glyphicon-time"></span>
<asp:Label ID="Date" runat="server" Text='<%# Bind("Time") %>'></asp:Label></small>
</div>
</div>
</ItemTemplate>
</asp:DataList>
And this is my code in .cs:
public void LoadChatbox()
{
Session["Name"] = "weiwei";
int waiwai = 1004;
//Request.QueryString["friendid"] = "waiwai";
Session["userid"] = 1005;
int userid = int.Parse(Session["userid"].ToString());
//int receiverid = int.Parse(Request.QueryString["friendid"]);
int receiverid = waiwai;
string name = Session["Name"].ToString();
DataSet ds = new DataSet();
ds.Locale = System.Globalization.CultureInfo.InvariantCulture;
IEnumerable<DataRow> query =
(from user in db.Users.AsEnumerable()
join ch in db.ChatHistories.AsEnumerable()
on user.Userid equals ch.Senderid
where ch.Senderid == userid && ch.Receiverid == receiverid || ch.Receiverid == userid && ch.Senderid == receiverid orderby ch.id
select new
{
Image = user.image,
Message = ch.message,
Time = ch.dateTime
})
as IEnumerable<DataRow>;
DataTable chatbox = query.CopyToDataTable<DataRow>();
ds.Tables.Add(chatbox);
DataList3.DataSource = ds;
DataList3.DataBind();
}
The
as IEnumerable<DataRow>
is causing yourquery
variable to benull
since the query will result in a collection of anonymous types, not a collection ofDataRow
objects.You'd either need to project to
DataRow
items or use other means to populate theDataTable
.Also, I would not call
.AsEnumerable()
on your data sets within the query if it's not necessary. It will force the entire table to be loaded into memory and the join done in Linq rather than on the database. If removingAsEnumerable
causes problems then you should find a different way to solve those problems.