今天接到一个项目,里面用到了好多的asp.net用户自定义控件,这是觉得如果能够给自定义控件添加自定义属性改多好啊,在百度和google找了好久也没有找到我想要的东西,无意中发现给用户自定义控件添加用户自定义属性居然这样简单,下面把代码贴出来供大家参考。
调用用户自定义控件文件的源代码:
文件名称:Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<%@ Register Src="user_Control/test.ascx" TagName="test" TagPrefix="uc1" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:test ID="Test1" runat="server" ShowMsg="http://blog.my400800.cn
" />
</div>
</form>
</body>
</html>
文件名称:Default2.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
用户自定义控件源代码:
文件名称:test.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="test.ascx.cs" Inherits="user_Control_test" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
文件名称:test.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class user_Control_test : System.Web.UI.UserControl
{
#region 用户自定义控件属性设定
private string myVar;
public string ShowMsg
{
//myVar
get { return myVar;}
set { myVar = value;}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (myVar);
}
}