用户控件学习-友情链接控件

集成数据绑定的用户控件-友情链接控件

(1)定义FriendLinkItem类,代表每个链接项

    [SerializableAttribute]    //必须可序列化
    public class FriendLinkItem
    {
        private string text;
        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                if(value!=string.Empty)
                    text=value;
                else
                    text="我的链接";
            }
        }
        public string navigateUrl;
        public string NavigateUrl
        {
            get
            {
                return navigateUrl;
            }
            set
            {
                string urlPattern=@"([\w-]+\.)+[\w-]+.([^a-z])(/[\w-: ./?%&=]*)?|[a-zA-Z\-\.][\w-]+.([^a-z])(/[\w-: ./?%&=]*)?";
                if(Regex.IsMatch(value,urlPattern))
                    navigateUrl=value;
                else
                    navigateUrl="http://www.cnblogs.com/zhouhb";
            }
        }
        public FriendLinkItem(string Text, string NavigateUrl)
        {
            this.Text = Text;
            this.NavigateUrl = NavigateUrl;
        }
    }
(2)创建用户控件,包含数据绑定控件GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    Width="138px">
    <Columns>
        <asp:HyperLinkField DataNavigateUrlFields="NavigateUrl" DataTextField="Text"
            HeaderText="常用链接" Target="_blank" >
            <ItemStyle HorizontalAlign="Center" />
        </asp:HyperLinkField>
    </Columns>
    <EmptyDataTemplate>
        请添加友情链接
    </EmptyDataTemplate>
</asp:GridView>

(3)用户控件在内部使用数据绑定的方法来显示Links属性所包含的友情链接项

        public List<FriendLinkItem> Links
        {
            get
            {
                return ViewState["Links"] as List<FriendLinkItem>;
            }
            set
            {
                ViewState["Links"] = value;
                GridView1.DataSource = value;
                GridView1.DataBind();
            }
        }

(4)页面中使用该用户控件
            if (!IsPostBack)
            {
                List<FriendLinkItem> links = new List<FriendLinkItem>();
                links.Add(new FriendLinkItem("博客园", "http://www.cnblogs.com"));
                links.Add(new FriendLinkItem("CSDN", "http://www.csdn.net"));
                links.Add(new FriendLinkItem("搜狐网", "http://www.sohu.com"));
                MyLink1.Links = links;
            }

运行效果:

posted @ 2011-05-23 16:06  zhouhb  阅读(416)  评论(1编辑  收藏  举报