我正在我的网络应用程序中开发一项功能。它是一个 cooking 社区。功能是在线讨论。用户可以在食谱下发表评论。我使用了一个 ListView 控件。我能够使用嵌套查询检索用户名。只能将一个数据集对象分配给 ListView 控件的 DataSource 属性。我需要用户名和评论值。正在显示用户名。我在显示该特定用户的评论时遇到问题。但我也需要显示用户的评论。我如何实现 显示评论的隐藏代码:
public void dispComments()
{
MySqlConnection con = new MySqlConnection("Server=localhost;Database=FreedomKitchen;Uid=root;Password=;");
con.Open();
MySqlCommand cmd = new MySqlCommand("select Username from User_Details where User_ID in(select User_ID from Recipe_Comments)", con);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "User_Comments");
ListView1.DataSource = ds;
ListView1.DataBind();
con.Close();
}
ListView 源代码:
<ItemTemplate>
<div id="div123">
<asp:Label ID="User"
runat="Server"
Text='<%#Eval("Username") %>'
width="850"
height="80"
/>
<%-- <asp:Label ID="Comment"
runat="Server"
Text='<%#Eval("Comment") %>'
width="850"
height="80"
/>--%>
</div>
</ItemTemplate>
<ItemSeparatorTemplate>
<br />
</ItemSeparatorTemplate>
</asp:ListView>
数据库: User_Details 表
User_ID//需要在listview项中显示这个
名字
姓氏
年龄
性别
国家
关于_用户
用户名
密码
User_Comments 表
Recipe_ID
用户名
Comment//需要显示这个listview项
最佳答案
将您的数据库查询更改为加入
评论和用户表并选择结果。
取消注释 ListView 的项目模板内的部分以同时显示注释。
将选中的结果集绑定(bind)到listview
编辑:
您可能需要在 User_Comments
表中包含一个 DateTime
列,因为一个用户可能有多个评论需要按时间顺序显示。
您可以在 dispComments()
方法中像这样更改代码
MySqlCommand cmd = new MySqlCommand("SELECT U.Username, R.Comment FROM Recipe_Comments R JOIN User_Details U ON R.User_ID = U. User_ID WHERE R.Recipe_ID = @RecipeID ORDER BY R.CommentDate DESC)", con);
cmd.Parameters.Add("@RecipeID", SqlDbType.Int).Value = value;
在您的ItemTemplate
<ItemTemplate>
<div id="div123">
<asp:Label ID="User" runat="Server" Text='<%#Eval("Username") %>' width="850" height="80" />
<asp:Label ID="Comment" runat="Server" Text='<%#Eval("Comment") %>' width="850" height="80" />
</div>
</ItemTemplate>
关于mysql - ListView -用户评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37108445/