How to re-use asp.net control on the page
How to re-use asp.net control on the page
I'm using web forms and have same text in two different blocks.
HTML:
<div class="div1">
<p>My text</p>
</div>
<div class="div2">
<p>My text</p>
</div>
I have to use asp.net controls.
The code I'm using
<asp:Literal runat="server" ID="lblText"></asp:Literal>
Is there any way to re-use this control for second text block instead of creating a clone of this control with another ID?
I can't use tags like <%= for this page.
<%=
lblText2.text = lblText.Text;
@VDWWD I know how to set text, but the question: is there any way to reuse this control and don't create another one?
– Gleb
Aug 20 at 10:21
Use a Repeater or create a User Control. Depends what you want exactly.
– VDWWD
Aug 20 at 10:22
1 Answer
1
Yes, you can encapsulate asp: Literal along with the HTML of your DIV within a UserControl and expose theText property.
asp: Literal
UserControl
Text
MyText.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyText.ascx.cs" Inherits="MyText" %>
<div>
<p>
<asp:Literal runat="server" ID="lblText" />
</p>
</div>
MyText.ascx.cs:
using System.Web.UI;
public partial class MyText : UserControl
public string Text
get
return lblText.Text;
set
lblText.Text = value;
And using it in WebForm:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="MyText.ascx" tagname="MyText" tagprefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:MyText ID="uc1MyText1" runat="server" Text="My text"/>
<uc1:MyText ID="uc1MyText2" runat="server" Text="My text 2"/>
<uc1:MyText ID="uc1MyText3" runat="server" Text="My text 3"/>
</form>
</body>
</html>
Result:

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In code behind use
lblText2.text = lblText.Text;.– VDWWD
Aug 20 at 10:14