Sie sind auf Seite 1von 4

9/1/2015

What is Web User Control?


• Using UserControl we can reuse both User
Interface and Code at different places within
the same webform or in different webforms of
Web User Control the same web application.
• They have a UI component (an .ascx file)
ASP.NET that works with the Visual Studio, and they
employ a matching class to manage the
execution.
• The .ascx file has a Control directive and a
class which is inherited from
"System.Web.UI.UserControl".
ranjan2130@gmail.com ranjan2130@gmail.com

Web User Control Creating a UserControl


• Unlike a Web Form, you can drag them onto • Launch Visual Studio  File  New  WebSite 
the Toolbox and drop them into a Web Form. ASP.NET Empty Website
• Go to Solution Explorer  Right Click  Add New
• When a UserControl is dragged and dropped
Item  Web User Control and give some appropriate
onto the webform (design view), name such as NameControl as in our example.
<%@Register directive is added to the
• A .ascx file and corresponding .cs file is added to
webform with TagPrefix and TagName as project. See the page source, a control directive
attributes. added to the control as
• For every instance of the UserControl in the <%@ Control Language="C#" AutoEventWireup="true"
form, the tagprefix and tagname are used. CodeFile="NameControl.ascx.cs" Inherits="NameControl" %>

• In normal page we have Page Directive here we have


control directive.
ranjan2130@gmail.com ranjan2130@gmail.com

NameControl:System.Web.UI.UserControl Design Interface


• Go to the .cs file you will see following: • Design interface for NameControl in .ascx
public partial class NameControl : System.Web.UI.UserControl file.
{
protected void Page_Load(object sender, EventArgs e) • Insert a Label and two Text Boxes and
{
change properties as:
}
<asp:Label ID="lblCaption" runat="server" Text="Caption"></asp:Label>
} <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
• A class NameControl inherited from
System.Web.UI.UserControl base class. And • Here in .ascx file you would not find any form
also it contain Page_load event. tag because this UserControl will be used as
a part of any page.

ranjan2130@gmail.com ranjan2130@gmail.com

1
9/1/2015

Consume Control Consuming User Control


• Now add a web page may be default.aspx. • And also see the control tag as
• Go to the Design view and drag and drop the <uc1:NameControl ID="NameControl1" runat="server" />

.ascx file to your web form. • Create two more instances of UserControl.
• A Control as you designed is added to your and change properties as:
page as a single unit comprising three <uc1:NameControl ID="nclName" runat="server" />
different controls. <br />
<uc1:NameControl ID="nclFathersName" runat="server" />
• Go to the source view of Default page. One <br />
<uc1:NameControl ID="nclMothersName" runat="server" />
additional directive is added to your page as <br />

shown below:
<%@ Register src="NameControl.ascx" tagname="NameControl"
• Add one button and change properties as:
tagprefix="uc1" %> <asp:Button ID="btnSubmit" runat="server" Text="Submit" />

ranjan2130@gmail.com ranjan2130@gmail.com

Consuming User Control Implement Property in Consumer


• Go to design view which is having Caption as • Go to the Default.aspx and add Caption
default text but we want to have respective properties with respective text. (You may
Captions to the controls.
need to rebuild web site before it to make it
• We cannot access Label's Text property because it
is a part of UserControl not a property of the page. available).
• To do so add a property to user control as <uc1:NameControl ID="nclName" runat="server" Caption="Name" />
<br />
public string Caption <uc1:NameControl ID="nclFathersName" runat="server"
{ Caption="Father's name" />
get
{ <br />
return lblCaption.Text; <uc1:NameControl ID="nclMothersName" runat="server"
} Caption="Mother's Name" />
set <br />
{
lblCaption.Text = value;
}
} • Run the project.
ranjan2130@gmail.com ranjan2130@gmail.com

Access Properties Handle Event and Run


• Now access (read) properties of text boxes designed • Handle button Click event to get FullName
in UserControl and used in WebPage. including Name, Father's Name and Mother's
• Go to .ascx file and add a public property named Name.
FullName
protected void btnSubmit_Click(object sender, EventArgs e)
public string FullName {
{ string str;
get str = nclName.FullName + "<br/>";
{ str += nclFathersName.FullName + "<br/>";
return txtFirstName.Text + " " + txtLastName.Text;
str += nclMothersName.FullName + "<br/>";
}
Response.Write(str);
set
{ }
string[] name = value.Split(' ');
txtFirstName.Text = name[0];
txtLastName.Text = name[1]; • Run it and enter Name, Father's Name and
}
} Mother's Name and Submit it and see result.
ranjan2130@gmail.com ranjan2130@gmail.com

2
9/1/2015

Note Palindrome Checker User Control


• The Controls in UserControl cannot be directly accessed in the • User controls are composite controls that contain child
webform thus for customizing the UserControl, public controls very much like binary composite controls do.
properties must be added to it. They’re very much like miniature Web Forms.
• These public properties in most of the circumstances wrap • To get a good idea of how Web User controls work, lets
around the controls which are added to the UserControl. build the palindrome checker as a User control.
• In the Example above FullName is the wrapper around • Build a new Website in Visual Studio.
txtFirstName and txtLastName Text Property; Caption is the • Right-click the site and click Add New Item. Select the
wrapper around lblCaption Text Property. Web User Control template and name the control
• User control does not have design time facility when used in a PalindromeCheckerUserControl.ascx.
WebForm. The Properties of the UserControl can be set by
• Switch to the Design view by clicking the Design tab.
setting the attributes for the UserControl tag used in WebForm.
Drag a Label, a TextBox, a Button, and another Label
• Change FullName property in design view but that is not from the Toolbox onto the User control. Delete the Text
reflected in Design view control. property from the second label so that it shows its
• Run it. It reflects. identifier.
ranjan2130@gmail.com ranjan2130@gmail.com

.ASCX Designer Code Code Behind .ascx


using System;
<%Control Language="C#" using System.Collections.Generic;
AutoEventWireup="true" using System.Linq;
using System.Web;
CodeBehind="PalindromeCheckerUserControl.ascx.cs" using System.Web.UI;
using System.Web.UI.WebControls;
Inherits="PalindromeCheckerUserControl"%> using System.Collections;
<asp:Label ID="Label1" runat="server" Text="Type in a public partial class PalindromeCheckerUserControl : System.Web.UI.UserControl
{
Palindrome:"></asp:Label> public event EventHandler PalindromeFound; // public event
ArrayList alPalindromes;
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> protected void Page_Load(object sender, EventArgs e)
<asp:Button ID="Button1" runat="server" Text="Check for Palindrome" {

OnClick="Button1_Click" /><br /> }


private String text;
<asp:Label ID="labelPalindromeStatus" runat="server" Height="38px" public string Text
{
Width="304px"></asp:Label><br /> <br />
get
<asp:Table ID="Table1" runat="server"> {
return text;
</asp:Table> }

ranjan2130@gmail.com ranjan2130@gmail.com

Code Behind .ascx Code Behind .ascx


set protected string StripNonAlphanumerics(string str)
{ {
text = value; string strStripped = (String)str.Clone();
this.alPalindromes =(ArrayList)this.ViewState["palindromes"]; if (str != null)
if (this.alPalindromes == null) {
{ char[] rgc = strStripped.ToCharArray();
this.alPalindromes = new ArrayList(); int i = 0;
} foreach (char c in rgc)
if (this.CheckForPalindrome()) {
{ if (char.IsLetterOrDigit(c))
if (PalindromeFound != null) {
{ i++;
PalindromeFound(this, EventArgs.Empty); }
} else
alPalindromes.Add(text); {
this.labelPalindromeStatus.Text = String.Format("This is a strStripped = strStripped.Remove(i, 1);
palindrome <br/><FONT size=\"5\" color=\"blue\"><B>{0}</B></FONT>",text); }
} }
else }
{ return strStripped;
this.labelPalindromeStatus.Text = String.Format("This is NOT }
a palindrome <br/><FONT size=\"5\" color=\"red\"><B>{0}</B></FONT>",text); protected bool CheckForPalindrome()
} {
this.ViewState.Add("palindromes", alPalindromes); if (this.Text != null)
this.BuildPalindromesTable(); {
}
}

ranjan2130@gmail.com ranjan2130@gmail.com

3
9/1/2015

Code Behind .ascx Code Behind .ascx


String strControlText = this.Text; foreach (string s in this.alPalindromes)
String strTextToUpper = null; {
strTextToUpper = Text.ToUpper(); TableCell tableCell = new TableCell();
strControlText = this.StripNonAlphanumerics(strTextToUpper); tableCell.BorderStyle = BorderStyle.Double;
char[] rgcReverse = strControlText.ToCharArray(); tableCell.BorderWidth = 3;
Array.Reverse(rgcReverse); tableCell.Text = s;
String strReverse = new string(rgcReverse); TableRow tableRow = new TableRow();
if (strControlText == strReverse) tableRow.Cells.Add(tableCell);
{ this.Table1.Rows.Add(tableRow);
return true; }
} }
else }
{ protected void Button1_Click(object sender, EventArgs e)
return false; {
} this.Text = this.TextBox1.Text;
} CheckForPalindrome();
else }
{ }
return false;
}
} • To test place control to a webpage and run
protected void BuildPalindromesTable()
{
this.alPalindromes = (ArrayList)this.ViewState["palindromes"];
the code.
if (this.alPalindromes != null)
{

ranjan2130@gmail.com ranjan2130@gmail.com

Thanks

ranjan2130@gmail.com

Das könnte Ihnen auch gefallen