组件化开发-用户控件开发-服务器控件开发

来源:互联网 发布:用java编写网页的步骤 编辑:程序博客网 时间:2024/04/30 10:29



public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            UserInput1.InputString = "请输入一个字串";

        UserInput1.MyClick += new MyClickDelegate(UserInput1_MyClick);
    }

    void UserInput1_MyClick(string str)
    {
        string script = "alert('第{0}次单击,输入字串为:{1}');";
        UserInput1.ClickCount++;
        script=string.Format(script,UserInput1.ClickCount,str);
        ClientScript.RegisterStartupScript(this.GetType(), "MyClick", script, true);

        UserInput1.InputString = "";
        UserInput1.Focus();
    }
}

 


友情链接  FriendLink2.ascx.cs

public partial class UserControl_FriendLink2 : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.baidu.com");
    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.google.com");

    }
    protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.sina.com.cn");

    }
    protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.sohu.com");

    }
}

 

--------------------------------------------------------------------------------------------

搜索页和母版页

 

-------------------------MasterPage.master----------------------------------- 

 

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
            //使用Session保存搜索文本
            Session["txtSearch"] = txtSearch.Text;
            Response.Redirect("~/Search.aspx");
    }
}

 

-----------------Search.aspx.cs------------------------------------------------

public partial class Search : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)  //如果去掉这句判断,会发现如果是直接访问搜索页面,则不能搜索,为什么?
        {
            string text = Session["txtSearch"] == null ? "" : Session["txtSearch"].ToString();
            if (text != null)
            {
                //查找到母版页上的控件
                TextBox txt = Master.FindControl("txtSearch") as TextBox;
                if (txt != null)
                {
                    txt.Text = text;
                }
                lblInfo.Text = "用户在母版页上输入了:" + text;
            }

        }
    }

}
-----------------------------------搜索页和母版页 end--------------------------------------------------

 

 

-----------------------------------------DynamicCreateControl------------------------------------------------------------

 

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            chks = new List<string>();
            ViewState["chks"] = chks;
        }
        else
            chks = ViewState["chks"] as List<string>;

        foreach (string chkText in chks)
        {
            CheckBox chk = new CheckBox();
            chk.Text = chkText;
            PlaceHolder1.Controls.Add(chk);
        }

    }

    private int ctlCount
    {
        get
        {
            return ViewState["ctlCount"] == null ? 0 : Convert.ToInt32(ViewState["ctlCount"]);
        }
        set
        {
            ViewState["ctlCount"] = value;
        }
    }

    private List<string> chks;
   
    protected void btnCreateControl_Click(object sender, EventArgs e)
    {
        CheckBox chk = new CheckBox();
        chk.Text = "复选框"+(++ctlCount);
        PlaceHolder1.Controls.Add(chk);
        chks.Add(chk.Text);
        ViewState["chks"] = chks;
    }
}

 

 

 

 

---------------------------web控件开发---------------------------------------------------------------------------

MyHyperLink.cs

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace MyWebControlLibrary
{
    public class MyHyperLink:HyperLink
    {

        public string RedirectPage
        {
            get
            {
                return ViewState["RedirectPage"]==null? "":ViewState["RedirectPage"].ToString();
            }
            set
            {
                ViewState["RedirectPage"] = value;

            }
        }

        public new string NavigateUrl
        {
            get
            {
                return base.NavigateUrl;
            }
            set
            {
                if (string.IsNullOrEmpty(RedirectPage))
                    base.NavigateUrl = value;
                else
                {
                    string url = "{0}?Page={1}";
                    url = String.Format(url, RedirectPage, value);
                    base.NavigateUrl = url;
                }
            }

        }
    }
}

 

----------------------------MyRGBControl.cs---------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyWebControlLibrary
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:MyRGBControl runat=server></{0}:MyRGBControl>")]
    public class MyRGBControl : CompositeControl
    {
        //三个标签
        private Label lblR = new Label();
        private Label lblG = new Label();
        private Label lblB = new Label();
        //三个文本框
        private TextBox txtR = new TextBox();
        private TextBox txtG = new TextBox();
        private TextBox txtB = new TextBox();
        //两个按钮
        private Button btnOK = new Button();
        private Button btnReset = new Button();
        //三个区间检验控件
        private RangeValidator validatorR = new RangeValidator();
        private RangeValidator validatorG = new RangeValidator();
        private RangeValidator validatorB = new RangeValidator();
        //三个必填项检验控件
        private RequiredFieldValidator requireR = new RequiredFieldValidator();
        private RequiredFieldValidator requireG = new RequiredFieldValidator();
        private RequiredFieldValidator requireB = new RequiredFieldValidator();


        /// <summary>
        /// 设置好各个控件的各种属性
        /// </summary>
        private void SetupControlProperites()
        {
            lblR.Text = "R:";
            lblG.Text = "G:";
            lblB.Text = "B:";

            txtR.ID = "txtR";
            txtR.Text = "0";
            txtR.Width = 40;
            txtG.ID = "txtG";
            txtG.Width = 40;
            txtG.Text = "0";
            txtB.ID = "txtB";
            txtB.Text = "0";
            txtB.Width = 40;

            btnReset.Text = "重置";
            btnReset.CommandName = "Reset";
            //btnReset.Click += new EventHandler(btnReset_Click);
            btnOK.Text = "确定";
            btnOK.CommandName = "OK";
            // btnOK.Click+=new EventHandler(btnOK_Click);

            validatorR.ControlToValidate = "txtR";
            validatorR.ErrorMessage = "颜色值必须为0~255";
            validatorR.MaximumValue = "255";
            validatorR.MinimumValue = "0";
            validatorR.Type = ValidationDataType.Integer;
            validatorR.Display = ValidatorDisplay.Dynamic;
            validatorR.SetFocusOnError = true;


            validatorG.ControlToValidate = "txtG";
            validatorG.ErrorMessage = "颜色值必须为0~255";
            validatorG.MaximumValue = "255";
            validatorG.MinimumValue = "0";
            validatorG.Type = ValidationDataType.Integer;
            validatorG.Display = ValidatorDisplay.Dynamic;
            validatorG.SetFocusOnError = true;

            validatorB.ControlToValidate = "txtB";
            validatorB.ErrorMessage = "颜色值必须为0~255";
            validatorB.MaximumValue = "255";
            validatorB.MinimumValue = "0";
            validatorB.Type = ValidationDataType.Integer;
            validatorB.Display = ValidatorDisplay.Dynamic;
            validatorB.SetFocusOnError = true;

            requireR.ErrorMessage = "必须输入颜色值";
            requireR.ControlToValidate = "txtR";

            requireG.ErrorMessage = "必须输入颜色值";
            requireG.ControlToValidate = "txtG";

            requireB.ErrorMessage = "必须输入颜色值";
            requireB.ControlToValidate = "txtB";

        }


        /// <summary>
        /// 布局所有的子控件
        /// </summary>
        protected override void CreateChildControls()
        {
            Controls.Clear();

            SetupControlProperites();

            Table tbl = new Table();
            TableRow tbr;
            TableCell tbc;
            //第一行
            tbr = new TableRow();

            tbc = new TableCell();
            tbc.Controls.Add(lblR);
            tbr.Cells.Add(tbc);

            tbc = new TableCell();
            tbc.Controls.Add(txtR);
            tbr.Cells.Add(tbc);

            tbc = new TableCell();
            tbc.Controls.Add(lblG);
            tbr.Cells.Add(tbc);

            tbc = new TableCell();
            tbc.Controls.Add(txtG);
            tbr.Cells.Add(tbc);

            tbc = new TableCell();
            tbc.Controls.Add(lblB);
            tbr.Cells.Add(tbc);

            tbc = new TableCell();
            tbc.Controls.Add(txtB);
            tbr.Cells.Add(tbc);

            tbl.Rows.Add(tbr);


            //第二行
            tbr = new TableRow();

            tbc = new TableCell();
            tbc.ColumnSpan = 6;
            tbc.Controls.Add(btnReset);
            tbc.Controls.Add(btnOK);
            tbr.Cells.Add(tbc);

            tbl.Rows.Add(tbr);
         

            //呈现表格

            Controls.Add(tbl);

            //添加6个验证控件

            Controls.Add(validatorR);
            Controls.Add(validatorG);
            Controls.Add(validatorB);

            Controls.Add(requireR);
            Controls.Add(requireG);
            Controls.Add(requireB);

            base.CreateChildControls();
        }

        #region "事件处理"

        //定义事件委托
        public delegate void ColorChangedDelegate(ColorChangedEventArgs e);
        //定义事件
        public event ColorChangedDelegate ColorChanged;

        public event EventHandler ColorReset;
        /*说明:
         *
         * 有两种事件处理方法:
         * 第一种是传统的事件处理方法,即在控件中给每个子控件的相应
         * 事件编码,在这些事件中激发复合控件的事件。
         * 如果要采用这种方法,注释掉OnBubbleEvent()函数
         * 在SetupControlProperites函数中给注释掉的两句取消注释:
          //btnReset.Click += new EventHandler(btnReset_Click);
          // btnOK.Click+=new EventHandler(btnOK_Click);
         *再取消以下两个函数btnOK_Click()和btnReset_Click()的注释即可.
         *
         * 第二种方式是使用事件冒泡,注释掉传统事件处理方式的所有代码,使用
         * OnBubbleEvent()函数统一激发事件。
         * 这是本控件默认使用的方法。
        */



        //protected void btnOK_Click(object sender, EventArgs e)
        //{
        //    int R = int.Parse(txtR.Text);
        //    int G = int.Parse(txtG.Text);
        //    int B = int.Parse(txtB.Text);
        //    System.Drawing.Color clr = System.Drawing.Color.FromArgb(R, G, B);
        //    if(ColorChanged!=null)
        //        ColorChanged(new ColorChangedEventArgs(clr));
        //}


        //void btnReset_Click(object sender, EventArgs e)
        //{
        //    txtR.Text = "0";
        //    txtG.Text = "0";
        //    txtB.Text = "0";
        //    if (ColorReset != null)
        //        ColorReset(this, EventArgs.Empty);
        //}


        /// <summary>
        /// 用冒泡法实现事件处理
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            Button btn = source as Button;

            if (btn != null)
            {
                switch (btn.CommandName)
                {
                    case "OK":  //处理“确定”按钮单击事件
                        int R = int.Parse(txtR.Text);
                        int G = int.Parse(txtG.Text);
                        int B = int.Parse(txtB.Text);
                        System.Drawing.Color clr = System.Drawing.Color.FromArgb(R, G, B);
                        if (ColorChanged != null)
                            ColorChanged(new ColorChangedEventArgs(clr));
                        return true;
                    case "Reset": //处理“重置”按钮单击事件
                        txtR.Text = "0";
                        txtG.Text = "0";
                        txtB.Text = "0";
                        if (ColorReset != null)
                            ColorReset(this, EventArgs.Empty);
                        return true;
                 
                      
                }
            }

             return base.OnBubbleEvent(source, args);
        }

        #endregion

    }

    /// <summary>
    /// 事件参数
    /// </summary>
    public class ColorChangedEventArgs : System.EventArgs
    {
        public System.Drawing.Color color;
        public ColorChangedEventArgs(System.Drawing.Color colorValue)
        {
            color = colorValue;
        }
    }
}

 

 

原创粉丝点击