前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="datalistwork2.aspx.cs" Inherits="datalistwork2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server"
onitemdatabound="DataList1_ItemDataBound" RepeatColumns="3"
RepeatDirection="Horizontal">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("classname") %>'></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("classid") %>' />
</td>
</tr>
<tr>
<td>
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<table>
<tr>
<td><a href='articleinfo.aspx?id=<%# Eval("ARTICLEID") %>' title='<%# Eval("title") %>'><%# Eval("title").ToString().Substring(0,5)+"....." %></a></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class datalistwork2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gettable();
}
}
private void gettable()
{
string str = ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
DataTable dt = null;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand com = con.CreateCommand())
{
com.CommandText = "select top 3 CLASSID,CLASSNAME from ArticleClass";
SqlDataAdapter da = new SqlDataAdapter(com);
dt = new DataTable();
da.Fill(dt);
}
}
this.DataList1.DataSource = dt;
this.DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
Label lb=e.Item.FindControl("Label1") as Label;
HiddenField hf = e.Item.FindControl("HiddenField1") as HiddenField;
if(lb!=null&&hf!=null)
{
DataList list = e.Item.FindControl("DataList2") as DataList;
if (list != null)
{
gettable(hf.Value,list);
}
}
}
}
private void gettable(string classid,DataList list)
{
string str = ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
DataTable dt = null;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand com = con.CreateCommand())
{
com.CommandText = "select top 2 * from articleinfo where classid=" + classid;
SqlDataAdapter da = new SqlDataAdapter(com);
dt = new DataTable();
da.Fill(dt);
}
}
list.DataSource = dt;
list.DataBind();
}
}