概述
//aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicDataList.aspx.cs" Inherits="DynamicDataList" %>
<!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:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
//aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class DynamicDataList : System.Web.UI.Page
{
private DataView GetAuthors()
{
SqlConnection cn = new SqlConnection(@"server=./SQLExpress;uid=sa;pwd=password;database=pubs");
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cn);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
cn.Close();
return ds.Tables[0].DefaultView;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataList d = new DataList();
d.ID = "dlstTest";
d.ItemTemplate = new MyColumn("h1", 200);
d.ItemDataBound +=new DataListItemEventHandler(d_ItemDataBound);
d.DataSource = this.GetAuthors();
d.DataBind();
this.form1.Controls.Add(d);
}
private void d_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{
HyperLink h;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
h = (HyperLink)e.Item.FindControl("h1");
if (h != null)
{
h.Text = ((DataRowView)e.Item.DataItem).Row["au_id"].ToString();
h.NavigateUrl = "Msg.aspx?id=" + h.Text;
}
}
}
}
public class MyColumn : ITemplate
{
private string pControlName; //控件名称
private int pWidth; //控件宽度
public MyColumn(string ControlName, int Width)
{
pControlName = ControlName;
pWidth = Width;
}
public void InstantiateIn(Control container)
{
HyperLink h = new HyperLink();
h.Width = pWidth;
h.ID = pControlName;
container.Controls.Add(h);
}
}
最后
以上就是鳗鱼海燕为你收集整理的动态创建DataList的全部内容,希望文章能够帮你解决动态创建DataList所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复