asp.net自定義控件

  這段時間一直想本身作個控件玩玩,本來準備作一個像repeater差很少 固然最初的設想用起來要比repeater方便,包括在CSS和一些JS,jquery的使用上面html

和repeater進行對比,可是作出來後發現代碼繞了好多,控件直接讀取數據庫的話還要封裝好讀取數據庫的代碼,若是不封裝在後期的使用過程當中會對整個項目都必jquery

定會有不少的約束。雖然這是個偏離原來目的的控件,可是對於初學者來講 應該還有參考價值。數據庫

下面貼出控件代碼:數組

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Drawing.Printing;
using System.IO;
using System.Data;
using System.Data.SqlClient;

[assembly: TagPrefix("XTB_MSList", "XXW")]
namespace XTB_MSList
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:XTB_MSList runat=server></{0}:XTB_MSList>")]

    public class XTB_MMSList : WebControl
    {
        #region Text屬性
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }
            set
            {
                ViewState["Text"] = value;
            }
        }
        #endregion

        #region 讀取的表名稱
        public string Xtb_Name
        {
            get
            {
                String s = (String)ViewState["Xtb_Name"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }
            set
            {
                ViewState["Xtb_Name"] = value;
            }
        }
        #endregion

        #region 讀取的HTML頁面地址
        public string Xtb_PathName
        {
            get
            {
                String s = (String)ViewState["Xtb_PathName"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }
            set
            {
                ViewState["Xtb_PathName"] = value;
            }
        }
        #endregion

        #region 讀取數據庫鏈接字符串的名稱
        public string Xtb_DName
        {
            get
            {
                String s = (String)ViewState["Xtb_DName"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }
            set
            {
                ViewState["Xtb_DName"] = value;
            }
        }
        #endregion

        #region 讀取顯示的行數
        public string Xtb_Count
        {
            get
            {
                String s = (String)ViewState["Xtb_Count"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }
            set
            {
                ViewState["Xtb_Count"] = value;
            }
        }
        #endregion

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (!DesignMode)
            {
                string connectString = ConfigurationManager.ConnectionStrings[Xtb_DName].ConnectionString;
                string htmls = GetInterIDList(Xtb_PathName);
                string outprint = DataListPrint(connectString, htmls);
                output.Write(outprint);
            }
            base.RenderContents(output);
        }
        /// <summary>
        /// 讀取數據庫,顯示數據替換字符串輸出到頁面上
        /// </summary>
        /// <param name="connectString">數據庫鏈接字符串</param>
        /// <param name="htmls">靜態頁面的內容</param>
        public string DataListPrint(string connectString, string htmls)
        {
            string outprint = "";
            var listName = TableList(htmls);
            char[] sp = { ','};
            string[] listname = listName.Split(sp);
            string listkey = "";
            for (int i = 0; i < listname.Length; i++)
            {
                listkey = listkey + listname[i].ToString() + ",";
            }
            listkey = listkey.Substring(0, listkey.Length - 1);
            string outhtmls = "";
            if (listkey.Length > 1)
            {
                DataTable dt = DBHelp.GetDataTable("select top " + Xtb_Count + " " + listkey + " from " + Xtb_Name, connectString);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < listname.Length; j++)
                    {
                        if (j==0)
                            outhtmls = htmls.Replace("{XTB_" + listname[j] + "}", dt.Rows[i][listname[j].ToString()].ToString());
                        else
                            outhtmls = outhtmls.Replace("{XTB_" + listname[j] + "}", dt.Rows[i][listname[j].ToString()].ToString());
                    }
                    outprint = outprint + outhtmls ;
                }
            }
            return outprint;
        }
        /// <summary>
        /// 提取前臺要顯示的字段名稱,並返回LIST
        /// </summary>
        /// <param name="htmls">靜態頁面內容轉化成的字符串</param>
        /// <returns>返回值 查詢的字段數組</returns>
        public string TableList(string htmls)
        {
            string ListName = "";
            int i = htmls.IndexOf("{XTB_");
            string s = htmls.Substring(i, htmls.Length - i);
            for (int l = 0; s.IndexOf("{XTB_") != -1; l++)
            {
                i = s.IndexOf("{XTB_");
                s = s.Substring(i, s.Length - i);
                string key = s.Substring(5, s.IndexOf("}") - 5);
                i = s.IndexOf("{XTB_");
                s = s.Substring(i + 5, s.Length - i - 5);               
                ListName += key + ",";
            }        
            ListName = ListName.Substring(0, ListName.Length - 1);
            return ListName;
        }
        /// <summary>
        /// 讀取html靜態頁面
        /// </summary>
        /// <param name="strfile">頁面名稱或地址路徑Xtb_PathName的屬性值</param>
        /// <returns>返回值 靜態頁面內容</returns>
        public string GetInterIDList(string strfile)
        {
            string strout = "";
            if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))
            {                
                StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default);
                String input = sr.ReadToEnd();
                sr.Close();
                strout = input;
            }
            return strout;
        }
    }
}

控件代碼就到此結束,下面講解使用過程:ide

須要使用控件時要先把生成的DLL文件引用到項目中去,post

頁面使用時須要輸入以下代碼<XXW:XTB_MMSList runat="server" Xtb_Count="5" Xtb_DName="SQLConnString" Xtb_Name="orders" Xtb_PathName="TEST.html" />測試

還有<%@ Register Assembly="XTB_MSList" Namespace="XTB_MSList" TagPrefix="XXW" %>this

而後在Web.config文件中添加數據庫鏈接字符串,鏈接字符串的name能夠隨意命名,示例:spa

    <connectionStrings>
        <add name="SQLConnString" connectionString="Data Source=.;Initial Catalog=Northwind;integrated security=true" providerName="System.Data.SqlClient;Pooling=true;MAX Pool Size=512;Min Pool Size=50;Connection Lifetime=300"/>
    </connectionStrings>

aspx頁面代碼示例:code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2"%>

<%@ Register Assembly="XTB_MSList" Namespace="XTB_MSList" TagPrefix="XXW" %>
<!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>
    <XXW:XTB_MMSList  runat="server" Xtb_Count="5" Xtb_DName="SQLConnString" Xtb_Name="orders" Xtb_PathName="TEST.html" />
    </div>
    </form>
</body>
</html>

根據aspx頁面中自定義控件的Xtb_PathName="TEST.html" 在項目或相應的位置處添加文件test.html,在這裏也能夠設置成test.txt。只須要文件存在就

能夠讀取而後顯示在頁面上,也能夠在這裏設置好CSS,顯示的時候會直接輸出在頁面上;

下面貼出test.html的代碼:

 

<div>
    {XTB_CustomerID}
</div>
<div>
    {XTB_OrderDate}
</div>
<div>
    {XTB_ShippedDate}
</div>

 

 

下面貼出個人測試頁面輸出後顯示的代碼以下:

 

<!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><title>

</title></head>
<body>
    <form method="post" action="Default2.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTYyNzE4MTUzN2RkJXbGr7tDft0VFyhd4U01D5uCJLGK9q/ycTM2X8SWPnw=" />
</div>

    <div>
    <span><div>
    VINET
</div>
<div>
    1996-7-4 0:00:00
</div>
<div>
    1996-7-16 0:00:00
</div>
<br><div>
    TOMSP
</div>
<div>
    1996-7-5 0:00:00
</div>
<div>
    1996-7-10 0:00:00
</div>
<br><div>
    HANAR
</div>
<div>
    1996-7-8 0:00:00
</div>
<div>
    1996-7-12 0:00:00
</div>
<br><div>
    VICTE
</div>
<div>
    1996-7-8 0:00:00
</div>
<div>
    1996-7-15 0:00:00
</div>
<br><div>
    SUPRD
</div>
<div>
    1996-7-9 0:00:00
</div>
<div>
    1996-7-11 0:00:00
</div>
<br></span>
    </div>
    </form>
</body>
</html>

 

從代碼能夠看到控件的標籤已經不存在,所有轉化爲要讀取的數據顯示在頁面上。因此能夠看作這個控件歸根究底就是一種字符的替換,替換了原先的字符顯示在

頁面上。只是省去了中間的代碼,固然 ,替換的代碼也已經都封裝在控件中。

相關文章
相關標籤/搜索