June 3, 2009

In the previous example, I showed how we can access data from user control. In this example, I will build on the previous example and load data from one user control to another.

I will add another user control to the application. The code for the user control is below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlPrac1.ascx.cs" Inherits="UserControlPrac1" %>
First name:
<asp:Label ID="LabelFirstName" runat="server" Text="First name label"></asp:Label><br />
Last Name:
<asp:Label ID="LabelLastName" runat="server" Text="Last name label"></asp:Label>


public partial class UserControlPrac1 : System.Web.UI.UserControl
protected void Page_Load(object sender, EventArgs e)
{ }

public string LastName
set { LabelLastName.Text = value; }

public string FirstName
set { LabelFirstName.Text = value; }

In the .ascx page, I have declared two Label controls LabelLastName and LabelFirstName. In the code behind, I have created two public methods that sets the value of the Label controls of the user control.

In the .aspx page, I am adding the user-control.

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

<%@ Register src="UserControlPrac.ascx" tagname="UserControlPrac" tagprefix="uc1" %>
<%@ Register src="UserControlPrac1.ascx" tagname="UserControlPrac1" tagprefix="uc2" %>

<!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>
<form id="form1" runat="server">
<uc1:UserControlPrac ID="UserControlPrac1" runat="server" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Second User Control:</p>
<uc2:UserControlPrac1 ID="UserControlPrac11" runat="server" />


In code-behind,

public partial class UserControlPracTest : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected void Button1_Click(object sender, EventArgs e)
Response.Write("first name: " + UserControlPrac1.FirstName);
Response.Write("<br/>last name: " + UserControlPrac1.LastName);

UserControlPrac11.FirstName = UserControlPrac1.FirstName;
UserControlPrac11.LastName = UserControlPrac1.LastName;


In code-behind for the page, when the Button is clicked, I am setting the public properties of the user control to values defined in the first user control.


sreedhar said...

Thank you so much.

Reference: Shahed Kazi at AspNetify.com