900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > ASP.NET基础教程-Web 自定义控件的使用-根据属性值从数据库中提取数据并在页面上自动

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

时间:2022-11-05 13:25:28

相关推荐

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

一、新建一个Web 控件库;

二、在WebCustomControl1.cs文件中编制如下代码:

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using ponentModel; 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 特

定字符和文本。

此类提供 服务器控件在将 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;

四、新建一个应用程序;

五、将生成的WebControlLibrary1.dll文件添加到工具栏中;

六、在工具栏中将添加的用户自定义控件添加到页面;

七、设置控件的Tablename属性为“成绩表”。 八、运行结果

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。