how to raise server control event(control defined inside user control) from host page?

I have built a user control(using c#,net 2.0,VS2005,MS-SQL server 2005),which contains set of 3 button,save,cancel and next and wud be reused/displayed in multiple pages.As the name says,they are suppose to update on save,reset the fields   on cancel and navigate to another page on next.How do i raise the onClick event for all of these button individually,from the individual host page?I do not have/do not prefer any logic,event handler etc.. defined in the user control for these buttons,since every host page have different set of parameters for save,cancel etc.Thanks for your help in advance.

0
nb123
6/24/2007 11:10:27 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

7 Replies
983 Views

Similar Articles

[PageSpeed] 32

Hello nb123,

In the User Control, you can use Parent to refer to the Page which the User Control is nested in. And use Parent.FindControl to access the controls in the Host Page, and use Parent.Parameters to access the Host Page's parameter, then you can determine what to do based on the controls and parameters on the Host Page.

Hope it helps,

Jessica


Jessica Cao
Sincerely,
Microsoft Online Community Support


“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
0
Jessica
6/26/2007 1:32:06 AM
Thanks Jessica.Can you give an example of how you do that or point me to some example?
0
nb123
6/26/2007 4:39:35 PM

Hello

Please create a base class in the App_Code folder and add public properties to the Base class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for BasePage
/// </summary>
public class BasePage:System .Web .UI .Page
{
 public BasePage()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    public string URL
    {
        get
        {
            return ViewState["url"] != null ? ViewState["url"].ToString() : "";
        }
        set
        {
            ViewState["url"] = value;
        }
    }
}

Make an aspx page inherits from the Base page class

public partial class testPage :BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
               URL = "abc";
    }
    
}
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="testPage.aspx.cs" Inherits="testPage" Title="Untitled Page" %>

<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
   </asp:Content>

and in the WebUserControl you could access the parent property use the following code

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string url = ((BasePage)this.Page).URL;
        Response.Write(url);
    }
}

Hope it helps,

Jessica

 


Jessica Cao
Sincerely,
Microsoft Online Community Support


“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
0
Jessica
6/27/2007 6:40:03 AM

 Thanks Jessica for your help ,though i am not sure if thats is what i am trying to accomplish.I am dealing with user control for the first time in this detail.Let me try to frame my problem in short here again,

-My user control contains bunch of button inside a panel

-When i click that button,i am expecting something to happen.In other words,i am trying to invoke the OnClick event for the button which is inside the user control through/from the main page.My main page,does not have any button directly placed on the designer.It just have the user control and  i do not know how to make it(main page) aware of the button,which  is inside the user control.Like 2 levels below from the main page.

:Main page-->>contains UserContols--->>which contains-->.button inside a panel control.

Thanks for your help again.

0
nb123
6/28/2007 10:10:16 PM

Hi nb123,

You can determine the Button Event in the main page when it fires the click event and post back to the server. Please try the following code

WebUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
&nbsp;<asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px">
    <asp:Button ID="Button1" runat="server" Text="Button" />
    <asp:Button ID="Button2" runat="server" Text="Button" />
    <asp:Button ID="Button3" runat="server" Text="Button" /></asp:Panel>

Test aspx

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

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            Label1.Text = GetPostBackControl(this).ID.ToString()+" has caused the post back";
    }
    public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page)
    {
        Control control = null;
        string ctrlname = page.Request.Params["__EVENTTARGET"];
        if (ctrlname != null && ctrlname != String.Empty)
        {
            control = page.FindControl(ctrlname);
        }
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it
        else
        {
            string ctrlStr = String.Empty;
            Control c = null;
            foreach (string ctl in page.Request.Form)
            {
                // handle ImageButton controls ...
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    ctrlStr = ctl.Substring(0, ctl.Length - 2);
                    c = page.FindControl(ctrlStr);
                }
                else
                {
                    c = page.FindControl(ctl);
                }
                if (c is System.Web.UI.WebControls.Button ||
                         c is System.Web.UI.WebControls.ImageButton)
                {
                    control = c;
                    break;
                }
            }
        }
        return control;
    } 

}

Hope it helps,

Jessica


Jessica Cao
Sincerely,
Microsoft Online Community Support


“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
0
Jessica
7/2/2007 4:02:12 AM

Hi,

The following code is for the Header.ascx.  A user control which displays the one HyperLink and one Link Button in a Panel.

<script language="c#" runat="server"> 

public void DoLogout(object sender, EventArgs e)
    {
        IsAuthenticated = false;
        FormsAuthentication.SignOut();
        pnlUser.Visible = false;
        pnlAnon.Visible = true;
    } 

 </script>

<body>

<asp:Panel
  ID="pnlUser"
  Align="right"
  Runat="Server">
  <asp:HyperLink
    ID="lnkUser"
  Runat="Server" />
 &nbsp;
 <a href="<%=ResolveUrl("~/sitejob/sitepass/listajob.aspx")%>">list job</a>&nbsp;&nbsp;
<asp:LinkButton
    Text="logout"
 OnClick="DoLogout"
        Runat="Server" />
 </asp:Panel>
 
 In Container page, register and declare the User control as below.

<div id="panelframe">
<usercontrol:header id="myheader" runat="server" />
</div>

When user clicks on the link button, the DoLogout method will be executed.

Database programming Using Visual basic 2005 and Csharp 2005

http://www.vkinfotek.com

 

 

0
vbsqlUser
7/2/2007 6:43:41 AM

I think you should use command for all your buttons




-----

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
bachbouch
7/2/2007 7:41:59 AM
Reply:

Similar Artilces:

Raise event from IE hosted windows user control and catch it in the Web Form that’s hosting the control
Hi. I have a web app that uses a IE hosted windows user control. I would like that, somehow, lounch an external event from that hosted control that I could catch in my web form’s code behind. If possible, please send a small sample project (bozesan_mihai82@yahoo.com). I would appreciate any suggestions! Thanks in advance! Hello, I am not sure of the *IE hosted windows user control*, but check this post to see if this helps you or not: Define a Custom Event inside UserControls HTH RegardsBilal Hadiar, MCP, MCTS, MCPD, MCTMicrosoft MVP - Telerik MVP...

How do you expose an event from a server control within an user control on an web form?
I have a calendar inside of an user control Simple.ascx The user control is sitting on my web form Simple.aspx. How do I access the VisibleMonthChanged event from my web form Simple.aspx? Is it possible? Yes Create Event in usercontrol which fires on page when VisibleMonthChanged event fires on usercontrol. Jigar Desai-----------------------Do not forget to "Mark as Answer" on the post that helped you. Ok, I created the event Public Event MonthChanged() in Simple.ascx.vb. Then I add the follow to Simple.aspx.vb Private Sub Simple_MonthChanged() Si...

Set the property of a server control inside a user control inside a Master Page
How do you set the property(ForeColor) of a server control(lnkInquiryReport2) located in a user control (LeftNavMain1) within a Master Page (default.master)? On the user control, expose a property of type color and bind this to the forecolor for the hyperlink control [keep some default value]. On your master page expose the user control as a property. On your content page, access the uc via the master's prop and the forecolor prop via the uc's prop and set it. Instead of exposing the uc from the master, you can also find the uc on the master - cast it to the correct type and then access th...

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...

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 ...

controlling an object in a web control from the page the web control is placed in
I have created a web control in vb.net that has an image button and an image. when it loads the image button is visible and the image is not. I want to be able from the page which "includes" the web control to set the image button to invisible and the image to visible. When I tried this, the main page didn't recognise the image button or the image (both < asp: objects). help would be gratefully appreciated. oh yeah, it's inline code so any code behind stuff will just confuse me ;) Some code please.-- Justin Lovell...

How do you control the placement of controls in a user define control
I have a user define control.  I put the control on the (C# Visual Studio 2008) page where I want them. When I run the program, the controls are all over the page.  How do I place them where they do not move form where I put them? You'll need to study the HTML output and see what it's producing, then start to look at how to do an HTML layout. hi, there are absolute and Relative position in html. I guess you must use relative position. For example, at design-time, you place a TextBox below an Image, at run-time, no matter what size is the image, the TextBox is alway bel...

Creating a User Control validator that validates a control on the page, rather than inside the control.
I'm trying to create a custom user control that is nothing more than a RangeValidator that validates other controls that lie on the page rather than inside the control itself... is this possible, is there a way to "bubble" it up. Thanks, G My answer to your other question regarding the CompareValidator applies here. If the custom control is in the same naming container AND does not implement INamingContainer, you can create a property that lets the user assign the control to validate. Internally assign the Validator.ControlToValidate property to the value of that property.-...

How to access individual controls from a form containing the web user control containing those controls
 Below is a block of code in my .aspx form named default.aspx. In this form I load a web user control. I then add it to a place holder control.(Lines 3 and 4 below) So how do I access the individual controls in my web user control? I want to set the properties on those controls, but I am baffled as to how to access the control. For example I have a text label control named "label3". How do I access this control. Because for example, under certain situations I want to hide that control. ( Label3.Visible = false;)  1    if(!Page.IsPostBack) 2&nb...

How to raised event in a user control from another user control?
How to raised event in a user control from another user control?Case: 2 user control UCA and UCB. In UCB, there is a refresh image button. In UCA, there is save Button.What I want is: When I click onSave button, some data will save into database. Then I want to raise the refresh button Click event, so that the data can be refreshed in UCB. UCA is put inside an updatePanel, UCB is put inside another Updatepanel.Here the requirement is: I can not refresh the whole page(otherwise, postback is the esay solution). Both Updatepanel must be partial rendering Take a look at this article: http://w...

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...

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! PeteWeb Design Nottingham, UK Well I can call BindPreview() from m...

Add user control from user control to web page
Hi there, I have a user control, that is inside another user control on a web page. From this user contfol, I need to add something to a place holder on the parent web page. I am having troubles referencing the placeholder correclty. I can get it fine as build time, but on runtime it kicks up the "Object reference not set to an instance of an object" error. Any ideas would be greatly appreciated. -------------------------------------------------------------- protected Civil_and_Corporate.candcadmin._default _default; ------------------------- Control objControl...

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 resources about - how to raise server control event(control defined inside user control) from host page? - asp.net.web-forms

Resources last updated: 12/4/2015 3:16:37 PM