用户控件学习笔记

从大一开始学到现在,自认为.net的知识基本掌握了,今天看了看学长的代码,发现现在的差距已经不再代码上面,而在于思想上面,学长们的经验要高于我们太多,总体来说还是写的代码太少了,需要多积累啊,言归正传。今天一学弟问我怎么写一个repeater的分页控件,然后始终发现repeater放里面不是,放外面也不是,最后还是学长一语点醒梦中人啊!直接上代码

先添加一用户控件tc

tc.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="tc.ascx.cs" Inherits="View_tc"%>

tc.ascx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class View_tc : System.Web.UI.UserControl

{

public Label label1;

 

protected void Page_Load(object sender, EventArgs e)

{

label1.Text = "测试";

}

}

该控件的功能就是修改页面一个label的值为测试,讲控件拖入页面test中(以前开发用vs2010,经常会出现卡死很长一段时间的情况,网上查了好多都没有找到解决办法,如有哪位大神知道如何解决,望不吝赐教),然后在页面中拖一个label,在page_load中使用控件修改label的text,代码如下

Test.aspx

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

 

<%@ Register Src="~/View/tc.ascx" TagPrefix="uc1" TagName="tc"%>

 

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<uc1:tc runat="server" ID="tc" />

</div>

</form>

</body>

</html>

 

test.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class View_test : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

tc.label1 = this.Label1;

}

}

这里涉及到c#语法里的引用传值,和c++语法略有区别,导致被学长训了一顿,惭愧,最后页面的效果如下

还有一个用法就是可以直接跟其他控件似得直接在引用控件的地方就给控件赋值

tc.ascx

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

 

<%@ Register Src="~/View/tc.ascx" TagPrefix="uc1" TagName="tc"%>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<uc1:tc runat="server" ID="tc" a="hellow" />

</div>

</form>

</body>

</html>

 

tc.ascx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class View_tc : System.Web.UI.UserControl

{

public Label label1;

public string a;

 

protected void Page_Load(object sender, EventArgs e)

{

if (a != null)

label1.Text = a;

else

label1.Text = "测试";

}

}

Test页面内容不变,执行结果如下

刹那间就感觉好神奇的样子,真是学无止境

posted @ 2013-05-11 23:02  血之君殇  阅读(466)  评论(0编辑  收藏  举报