Web User Control to Web User Control...

Hi, I have 2 User controls on a page and want Control1 to call a method of Control2. Is this Possible?

Example:

Con1 = Datalist showing products, each with a Quantity Box and a Button.

Con2 = Repeater showing Cart Preview (name, Price)

in page.aspx.

When I click on the button on the DataList in Con1 it adds the item into the Session based Cart. However it does not update the Cart Preview. I need to call BindPreview() in Con2 in order to update the Cart Preview...

Does that make sense? argh! any help much appreciated!

Pete


Web Design Nottingham, UK
0
pete_m
1/4/2006 2:38:55 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

10 Replies
1763 Views

Similar Articles

[PageSpeed] 28

Well I can call BindPreview() from my Control2 by using

cp1.BindPreview();

But I am getting a NullReferenceException error when calling the method from another control. Here is the code for the method:

public void BindPreview()
{
  objCartDT1 = (DataTable)Session["Cart"];
  RptCartPreview.DataSource = objCartDT1;
  RptCartPreview.DataBind();
}

I am getting the error on the first line.....any ideas? Cant seem to find this anywhere


Web Design Nottingham, UK
0
pete_m
1/4/2006 3:47:44 PM
Create an event in Control1 and handle the event in the page that contains the control.  From the page that contains the control you can then call your BindPreview for control2.

Example:

1.  Create 2 user controls named control1.ascx and control2.ascx.
2.  Create one page called WebForm1.aspx.
3.  Open control1.ascx and add a button named Button1.
4.  Open control1.ascx.cs and add the following code inside the control1 class:
        protected System.Web.UI.WebControls.Button Button1;

       // Define the event
        public event EventHandler BindControl2;

       // Notify the object registered object (EventHandler(ctrl1_BindControl2))
        protected virtual void OnBindControl2(System.EventArgs e)
        {
            if (BindControl2 != null)
            {
                BindControl2(this, e);
            }
        }
       // Raise the event
        private void Button1_Click(object sender, System.EventArgs e)
        {
            OnBindControl2(e);
        }
5.  Open control2.ascx.cs and add the following code inside the control2 class:
        public void BindPreview()
        {
            Response.Write("Bind Preview worked");
        }
6.  Open WebForm1.aspx and add both user controls to the page separated by breaks <br>.
7.  Open WebForm1.aspx.cs and add the following code to the WebForm1 class:
        protected control1 ctrl1;
        protected control2 ctrl2;

        private void Page_Load(object sender, System.EventArgs e)
        {
             // Register the event handler
            ctrl1.BindControl2 += new EventHandler(ctrl1_BindControl2);
        }

       // Define the eventhandler
        private void ctrl1_BindControl2(object sender, System.EventArgs e)
        {
            ctrl2.BindPreview();
        }

You are basically creating an event on your user control (control1) so that your container (WebForm1) can register the eventhandler with that event.  From WebForm1 you can access the second user control (control2) just as you do any other control (by reference) and execute it's public methods.

Hope this helps!

Paul
0
eccsolutions
1/4/2006 10:24:05 PM

Hi Paul, Thanks for the response,

You may have to bear with me Im afraid - I tried out the above (to the letter) and I'm getting a NullReferenceException on the line

 ctrl1.BindControl2 += new EventHandler(ctrl1_BindControl2);

in webform1. Any ideas...

Thanks again,

Pete



Web Design Nottingham, UK
0
pete_m
1/5/2006 9:51:57 AM
Paste the full error code.  Should not be getting that error.  Sounds like you forgot to place the usercontrols on WebForm1.aspx like so:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="codetestsc.WebForm1" %>
<%@ Register TagPrefix="uc1" TagName="control1" Src="control1.ascx" %>
<%@ Register TagPrefix="uc1" TagName="control2" Src="control2.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <title>WebForm1</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body>
        <form id="Form1" method="post" runat="server">
            <uc1:control1 id="ctrl1" runat="server"></uc1:control1><br><br><br>
            <uc1:control2 id="ctrl2" runat="server"></uc1:control2>
        </form>
    </body>
</HTML>

Paul
0
eccsolutions
1/5/2006 2:32:05 PM

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

on the line: ctrl1.BindControl2 += new EventHandler(ctrl1_BindControl2);

 

 


Web Design Nottingham, UK
0
pete_m
1/5/2006 2:36:54 PM

oops! my fault - I had the Control IDs as "Control1" rather than "ctrl"

Thanks for the help - It's an extremely useful example  :)

Pete


Web Design Nottingham, UK
0
pete_m
1/5/2006 3:47:21 PM
Did you add the usercontrols to the WebForm1.aspx page with the ID's ctrl1 and ctrl2?  The error is telling me that the object reference ctrl1 is not set to an instance of an object.  Make sure you add the following to WebForm1.aspx:

Place these at the top of the page with your Page Directive:

<%@ Register TagPrefix="uc1" TagName="control1" Src="control1.ascx" %>
<%@ Register TagPrefix="uc1" TagName="control2" Src="control2.ascx" %>


Place these inbetween the <form> tags:

<uc1:control1 id="ctrl1" runat="server"></uc1:control1><br><br><br>
<uc1:control2 id="ctrl2" runat="server"></uc1:control2>

Paul
0
eccsolutions
1/5/2006 3:52:55 PM

I'm using VWD Express (C#) - and don't really know what I'm doing - but had to make the following changes (in bold) to Paul's example to get it to work:

1.  Create 2 user controls named control1.ascx and control2.ascx.
2.  Create one page called WebForm1.aspx.
3.  Open control1.ascx and add a button named Button1.
4.  Open control1.ascx.cs and add the following code inside the control1 class:
       
protected System.Web.UI.WebControls.Button Button1;

       // Define the event
        public event EventHandler BindControl2;

       // Notify the object registered object (EventHandler(ctrl1_BindControl2))
        protected virtual void OnBindControl2(System.EventArgs e)
        {
            if (BindControl2 != null)
            {
                BindControl2(this, e);
            }
        }
       // Raise the event
        private public void Button1_Click(object sender, System.EventArgs e)
        {
            OnBindControl2(e);
        }
5.  Open control2.ascx.cs and add the following code inside the control2 class:
        public void BindPreview()
        {
            Response.Write("Bind Preview worked");
        }
6.  Open WebForm1.aspx and add both user controls to the page separated by breaks <br>.

6a.  Rename them from Control1 and Control2 to ctrl1 and ctrl2.

7.  Open WebForm1.aspx.cs and add the following code to the WebForm1 class:
        protected control1 ctrl1;
        protected control2 ctrl2;

        private void Page_Load(object sender, System.EventArgs e)
        {
             // Register the event handler
            ctrl1.BindControl2 += new EventHandler(ctrl1_BindControl2);
        }

       // Define the eventhandler
        private void ctrl1_BindControl2(object sender, System.EventArgs e)
        {
            ctrl2.BindPreview();
        }

Reasons I made the changes:

protected System.Web.UI.WebControls.Button Button1;
- Error 1 The type 'control1' already contains a definition for 'Button1'

private public
- Error 2 'control1.Button1_Click(object, System.EventArgs)' is inaccessible due to its protection level

6a.  Rename them from Control1 and Control2 to ctrl1 and ctrl2.
VWD Express names the Controls to Control1 and Control2 by default.

protected control1 ctrl1;
protected control2 ctrl2;
Error 4 The type 'WebForm1' already contains a definition for 'ctrl1'
Error 5 The type 'WebForm1' already contains a definition for 'ctrl2'

Please let me know if I've misunderstood something or need to have dealt with the errors in a different way.

Thanks very much.

Regards

Gary


Gary Bartlett
gb at prodsol dot co dot nz
+64 9 473-9530
+64 21 776-390
http://www.prodsol.co.nz - Dramatic improvement through pattern-level intervention
0
GaryBartlett
4/25/2006 2:25:58 AM
I have a simpler problem -- I want the click event for a button on the parent page to make the child control refresh its data.  The parent has a form that results in a row being added to a database, and the child has a view of the pertinent rows.  On submitting the form, the table needs to be refreshed...

So I went through this example, and got it working, except the compiler was flagging the equivalent statement for
public event EventHandler BindControl2;
telling me that "BindControl2" was never used.

Long story short, I ended up commenting out ALL the event handler business, and everything I needed the control to do could be in its Page_Load().  The only think left was the InitializeComponent() line:

this.btn1.Command += new System.Web.UI.WebControls.CommandEventHandler(this.btnClick);


In my real application, I'd used <input type="button">s instead of <asp:button>, so I changed those to get the .Command event for the object...  and I'm back where I started.  The control's Page_Load() refresh of the database is either not happening, or it's happening BEFORE the database row is inserted.

Any clues??

Tom von Alten
http://fortboise.org/
0
tva
6/20/2006 8:45:52 PM
> The control's Page_Load() refresh of the database is either not
> happening, or it's happening BEFORE the database row is inserted.


Indeed.  Problem was the control's Page_Load() executed and "refreshed"
the table with stale data, THEN the click eventhandler did the DB update.
Basic page life cycle issue.

Solution is to explicitly list the control in the page's variables,
    protected UserControl1 uc1;
(where uc1 is the id given to the control in the .aspx) and then
reference the control's method in the click eventhandler,
    uc1.updateHistory();
after the DB update. For efficiency, the control's Page_Load() only
calls updateHistory if !Page.IsPostBack.  Nothing special needed vis a vis
eventhandler declaration or registration.


Tom von Alten
http://fortboise.org/
0
tva
6/21/2006 9:27:31 PM
Reply:

Similar Artilces:

access controls on web user control x from web user control Y
I have 2 web users controls in a page and I would like to get or set the selected values of a few dropdown boxes on web user control X from web user control Y and I also would like to know how to access functions that are on a web user control X from a web user control Y, is this possible? How can I do it? User can access and set the values of the User Control from .aspx page through properties,using javascript and in code-behind of aspx page.The details of it are shown below Using PropertiesIf the Sample.ascx control has two textboxes and submit button.You can access the valu...

web controls and web user control
i have a problem in a web form , I have a webform that contains a web user control which in turn contains a html input form ,the web control events don't fire up ,When I click button ,no effect ,I don't know what is the effect of the html form which is in the web user control on the web controls in the web form ?? can any one help me the web control event should be handle in the code behind page, is the event handler for the button you are clicking registered? You can try double clicking the button, should give you the default btn_click event handler in code behind. Also, make ...

Persisting data in a web user control, which contains a list of other web user controls.
 Hi All, I have a control I've created, which can have a number of child controls - also user controls - stored as an ArrayList, which can be added wither a design time or programmatically.My problem is when I add to the list programmatically, it doesn't persist them. So if I add 3 child controls in step 1 of a wizard, with the aim that those three will be visible inside the parent in step 3, what happens is that the parent has no child controls and the item count is 0.Can anyone help? Thanks in advance.Code:Parent Control Markup: <%@ Control Language="C#" Auto...

Web user control inside update panel replace with another web user control
 Hi there. I have a page with a menu. an and then the content. My thing is. That i have the update panel, and inside that i have a regual panel in which i add the Web User Controls i need. Which all works fine. My problem is. That i i have a submit funcion on almoast all the Web User controls. What i would like is that i inside that update panel, can dispose the original Web user Control and then add a response Web User Control. In normal language. Is there a way that i can load one web user control into antoher and then disposose the original? Thanks in advance hello. well, what ...

Web Form and Web User Control
Hello, I have a Web User Control (ascx) that includes a button. This button has an onclick event method. This Web User control is included into a Web Form. (thru LoadControl). However, when I click on the button, the event method is not executed. What should I include in order it works fine? Thanks in advance. GAA. Using Loadcontrol is using dynamic controls and when using dynamic controls you must recreate the same dynamic controls ono postback to econstruct the page control tree. It is best if you do this during the Page PreInit event. How complex are your controls ...

Single page with multiple user web controls VS Multiple page with specific user web controls
I have a question regarding single page with multiple user web controls vs multiple page with specific user web controls   Option 1: I am of the opinion to have multiple pages with specific user web controls and use an object to store all the information as the user navigates through the application. And finally at the end, read this object and save all the information to the backend database.   Option 2: My respected team member suggests that we have only one page, with all the specific user web controls and not use an object, instead show/hide the user web controls based ...

What is the difference between a Web User Control and a Web Custom Control
Hi ,please could you answer for the following question with example. i know wht they are. but i want to know hw they are existing in web pages with simple example. What is the difference between a Web User Control and a Web Custom Control?  Thanks in AdvanceDilip    Check this out .... hope these might help you out... http://support.microsoft.com/kb/893667http://msdn2.microsoft.com/en-us/library/aa651710(VS.71).aspx itsUrDAY  Hi, See the following URLs: https://msdn2.microsoft.com/en-us/library/fb3w5b53(VS.71).aspx(Introduction to Web User Contr...

change layout of web controls in web user control
Hi I have create a user control with 3 asp:textbox in it. I would like to reuse the same 3 textboxes in 2 seperate web pages. In one case I want them to appear in  a row (as search parameters) and in the other I want them to appear in a column(to add a new object)..  Can I do change layouts using CSS or something? Hi,    Here is a solution to your question for your reference. Create a web user control as the following <%@ Control Language="C#" AutoEventWireup="true" CodeFile="DynamicalUserControl.ascx.cs" Inherits="DynamicalUserControl" %><asp:Panel ID="...

Use Web Custom control or Web User control?
Friends,  I have a generic aspx page and its functions which is used in many .NET web application. The generic page contains a HTML Div control, server drop down list, server buttons, server textbox and it have different server and client functions to do its tasks for calling aspx pages in web applications. My problem is I do not know whether I should make that generic page as a web user control (but this is tedious because all other application folders must store frontpage aspx and code behind files of the generic page) or as a web custom control (This seems to be good beca...

Server Web User Control or Web Custom Control
Ok, I made a DataGrid I like, stuck it in a Web Control Lib, and then to my toolbar. Now I want to take my nice little control and add it to a greater control, maybe place some buttons around it etc. I could always inherit from it in a new custom control and dynamically add the buttons, but I thought about using a Web User Control. I thought I could easily create a Web User Control, drop on my grid and the buttons on a form, and expose some properties and events, but once I got into it, I got a feeling that this isn't what a Web User Control is for. When designing a control li...

I have a web user control being used by another web user control, but the one being used will not display the labels in the resx file.
I am using DotNetNuke version 3.13 (might be 3.013) on a Window's XP machine, SP2. I have what I find to be an extremely odd situation. I have a project called TDS.Controls. This project is a web control library. Each control has its own resx file, which is located in the App_LocalResources directory. Each control inherits from Framework.UserControlBase, just like DotNetNuke's User control in DNN\Controls\User.ascx.vb. As a matter of fact, this control is doing the exact same thing I am trying to do. It is a web user control with its own resx file being used by another web user control (See ...

custom web user control and web form
Guys,          I am trying to develop a context menu control for all of my pages. what i am trying to do is that i want the control to pick a datasource from the markup and then check whether its an xml file or a datatable. I created a class called datasource.   /**************************DataSource Class****************************/  public class DataSource { /// <summary> /// This is to identify unique elements from the markup /// </summary>protected string _ID; /// <summary> /// This will be the Datasource ID e...

Web User Control Not rendering in Web Form
I have created a Web User control that is made up of a Multiview with 2 views inside the Multiview. I have buttons on both views and a gridview on 1 view. My question is when I drop this Web User Control on a Web Form all I see is [MultiView"MultiView1"] and when I view the from in the browser I dont see the Web User Control. I was wondering if someone could please tell me why the Web User Control is not displaying or rendering.     Thanks In Advance Hi, Please check your aspx file for correct reference, like following example: TestControl.ascx:<%@ Control ...

Javascript inside "web user control" not run if load "web user control" under ajax UpdatePanel
I have this problem and please if some can help me, I place here a sample code to see, but in my real problem the web user control have a very complicate javascript. I have a web user control that have some javascript inside, let say for example.1 <script type="text/javascript" > 2 function RunMe() 3 { 4 alert("Client id:<%=ClientID%>"); 5 } 6 </script> 7 8 9 <a href="javascript:RunMe()">Run javascript</a> a simple call to a simple javascript, inside the web user control And now I have...

Web resources about - Web User Control to Web User Control... - asp.net.web-forms

Control - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

WA bushfires: Firefighters work through the night to control several blazes
Firefighters in Western Australia are working through the night to control and contain several blazes.

MAZEL TOV, HILLARY: Clinton Wins Gun Control Award From Major Anti-Bill of Rights Group
... restrictions on the freedoms protected by the Constitution is not a sign of character, but a clear indication of blind adherence to a gun control ...

Brussels Pushes Gun Control In Wake of Paris Attacks
Europeans double down on gun control after terrorists murder defenseless civilians

The Legend of Zelda: Twilight Princess Wii U will likely support Wiimote and Nunchuk controls
Well this is interesting. Fans have been speculating as to the control schemes that will be supported in The Legend of Zelda: Twilight Princess ...

Mind-Control Bacteria Stop You From Eating Too Much
Gut microbes release proteins that stop the brain from thinking you're still hungry.

USB Volume Control
... computer speakers, they often have a volume knob you can mount somewhere on your desk so you aren’t dependent on the onboard volume control. ...

ICYMI: Even the AP couldn’t validate any of Hillary’s gun control nonsense
... – not 200 as she claimed . Asked to explain the discrepancy, Clinton’s campaign pointed to 2013 statistics from the Centers for Disease Control ...

Over-The-Counter Birth Control Empowers Women And Pharmacists In Oregon And California
Over-the-counter birth control is coming to Oregon and California. There’s an enactment of new laws on the horizon that will allow pharmacists ...

In this Dark Fairy Tale, a Sheltered Young Girl Seizes Control of Her Future
“In a family headed by a tyrannical father, the younger daughter will regain her freedom on her birthday.” It’s a simple synopsis, but Blood ...

Resources last updated: 11/28/2015 2:02:55 PM