您的位置:首页 > 编程语言 > ASP

ASP.NET基础教程-Web 自定义控件的使用-根据属性值从数据库中提取数据并在页面上自动生成一个表格

2008-01-06 12:36 1266 查看


一、新建一个Web 控件库;
二、在WebCustomControl1.cs文件中编制如下代码:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace WebControlLibrary1
{
/// <summary>
/// WebCustomControl1 的摘要说明。
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
public class WebCustomControl1 : System.Web.UI.WebControls.WebControl
{
private string text;//存储用户输入的文本内容
public string tablename;//存储用户输入的属性值
[Bindable(true),Category("Appearance"), DefaultValue("")]
Public string Tablename //添加用户自定义文本输出次数的属性
{
get {
return tablename;
}
set
{
tablename=value;
}
}
public string Text //添加用户自定义文本属性
{
get
{
return text;
}
set
{
text = value;
}
}
/// <summary>
/// 将此控件呈现给指定的输出参数。
/// </summary>
/// <param name="output"> 要写出到的 HTML 编写器 </param>
//protected访问仅限于包含类或从包含类派生的类型。
使用 override 修饰符来修改方法、属性、索引器或事件。
HtmlTextWriter类在 Web 窗体页上写出一系列连续的 HTML 特
定字符和文本。
此类提供 ASP.NET 服务器控件在将 HTML 内容呈现给
客户端时所使用的格式化功能。
protected override void Render(HtmlTextWriter output)
{
SqlConnection con=new SqlConnection(@System.Configuration.ConfigurationSettings.AppSettings["server"]);
con.Open();
string oSql="select count(id) from sysobjects where name='"+tablename.ToString()+"'";
SqlCommand comm=new SqlCommand(oSql,con);
int jl=(Int32)comm.ExecuteScalar();
con.Close();
if(jl>0) {
con.Open();
oSql="select * from "+tablename.ToString();
SqlDataAdapter da=new SqlDataAdapter(oSql,con);
DataSet ds=new DataSet();
da.Fill(ds,"Query");
con.Close();
string Text_Value="";
for(int i=0;i<ds.Tables["Query"].Rows.Count;i++){
Text_Value=Text_Value+"<TR>";
for(int j=0;j<ds.Tables["Query"].Columns.Count;j++){
Text_Value=Text_Value+"<TD>"+ds.Tables["Query"].Rows[i][j].ToString()+"</TD>";}
Text_Value=Text_Value+"</TR>";}
output.Write("<TABLE id='Table1' style='Z-INDEX: 115; LEFT: 0px; POSITION: absolute; TOP: 0px'
cellSpacing='1' cellPadding='1' width='300' border='1'>"+Text_Value.ToString()+"</TABLE>");
}
else{output.Write("对不起,找不到数据源,请确认你输入到“Tablename”属性的表名在数据库中存在");}
}
三、将控件编译生成WebControlLibrary1.dll;
四、新建一个ASP.NET应用程序;
五、将生成的WebControlLibrary1.dll文件添加到工具栏中;





六、在工具栏中将添加的用户自定义控件添加到页面;
七、设置控件的Tablename属性为“成绩表”。



八、运行结果




本文出自 “晨星工作室 软件培训项..” 博客,请务必保留此出处http://chenxing.blog.51cto.com/240526/58197
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐