I have a user control, which is added to another user control. The nested user control is built up of a GridView, an image button and a link button. The nested user control is added to the outer control as a collection object based upon the results bound to the GridView.
The problem that I have is that my link button doesn't work. I click on it and the event doesn't fire. Even adding a break point was not reached. As the nested user control is added a number of times, I have set image button to have unique ids and also the link button. Whilst image button works correctly with its JavaScript. The link button needs to fire an event in the code behind, but despite all my efforts, I can't make it work. I am adding the link button to the control dynamically. Below is the relevant code that I am using:
public partial class ucCustomerDetails : System.Web.UI.UserControl
{
public event EventHandler ViewAllClicked;
protected override void CreateChildControls( )
{
base.CreateChildControls( );
string strUniqueID = lnkShowAllCust.UniqueID;
strUniqueID = strUniqueID.Replace('$','_');
this.lnkShowAllCust.ID = strUniqueID;
this.lnkShowAllCust.Click += new EventHandler(this.lnkShowAllCust_Click);
this.Controls.Add(lnkShowAllCust);
}
protected override void OnInit (EventArgs e)
{
CreateChildControls( );
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
base.EnsureChildControls( );
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CreateChildControls( );
}
}
protected void lnkShowAllCust_Click(object sender, EventArgs e)
{
this.OnCustShowAllClicked(new EventArgs ( ));
}
protected virtual void OnCustShowAllClicked(EventArgs args)
{
if (this.ViewAllClicked != null)
{
this.ViewAllClicked(this, args);
}
}
}
I have been stuggling with this problem for the last 3 days and have had no success with it, and I really do need some help.
Can anyone please help me?
My LinkButton wasn't firing it's Click event, and the reason was I had its CausesValidation property set to True. If you don't want the link to validate the form, be sure to set this to False.
Try adding your click event to the linkbutton tag:
<asp:LinkButton runat="server" OnClick="linkShowAllCust_Click" />
Or adding it to your Page_Load:
Page_Load(object sender, EventArgs e)
{
this.lnkShowAllCust.Click += new EventHandler(this.lnkShowAllCust_Click);
}
Is the usercontrol within the gridview? If so register the event handler on the gridview's onrowcreated event.
It appears that you have a viewstate issue. Because the control isn't there when the viewstate is loaded the application doesn't know how to hook up the event to be fired. Here is how to work around this.
You can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
If IsPostBack Then
CreateMyControls()
End If
End Sub
I had the same issue. I had viewstate="false" on the page I was adding the control to. (on the aspx page)
Related
I'm trying to add a custom control to a panel (containing a "form" to input data) during a button click event and I want to access it's methods like .Validate() after this data has been inputted. But when I try to do so the ctrl comes with null value.
Here's part of my code :
protected void btnNext2_Click(object sender, EventArgs e)
{
...
ctrlCompliance = (Compliance)LoadControl("../../ascx/SRM/Compliance.ascx");
ctrlCompliance.ReadOnly = false;
pnlCompliance.Controls.Add(ctrlCompliance);
...
}
protected void btnNext3_Click(object sender, EventArgs e)
{
...
ctrlCompliance = pnlCompliance.Controls[0] as Compliance;
ctrlCompliance.Validate() <- this is allways null
...
}
I cannot use Page_Init as most of the solutions propose and really need to load it only during that button click. Did someone had the same problem as me?
You should load it anyway using Page_Init, but set its visible property to False. Then using javascript or code-behind you can change its visible property to True when you need to show the print button.
So move:
ctrlCompliance = (Compliance)LoadControl("../../ascx/SRM/Compliance.ascx");
ctrlCompliance.ReadOnly = false;
pnlCompliance.Controls.Add(ctrlCompliance);
to Page_Init
I made researching about this subject I could not find proper answer.
In my default.aspx page, I have a treeview. Codes are in default.aspx like below:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Control ucont;
if (TreeView1.SelectedNode.Value == "Yeni Dönem")
{
ucont = LoadControl("usercontrols/yenidonem.ascx");
PlaceHolder1.Controls.Add(ucont);
}
else
{
ucont = LoadControl("usercontrols/tabloktar.ascx");
PlaceHolder1.Controls.Add(ucont);
}
}
I load user controls dnynmicaly. User controls are have button control. I can not fire user control's button click when I load it dynamcally. How can I solve this ?
Thanks.
First of all, I would not recommend adding control dynamically later than in Page_Load event. Other things to remember is that You should add it on each page load and assign unique ID value the control that does not change between postbacks.
In this case, the easiest way would be to always add both controls to the page and show appropriate one using Visibility property.
If that's not suitable for You, try to move the code from TreeView1_SelectedNodeChanged to the Page_Load event and load appropriate control on each postback until it should be changed to another one.
I haven't tested this, so if You have any issues when using thise answer, let me know in the comments and I'll try to help.
For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via Page.FindControl gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
I've successfully loaded controls dynamically in Page_Load before. The only thing I found I had to be careful of was to ensure that if I did a postback, the same controls were loaded in subsequent page_load to ensure that the view state didn't get corrupted... all events etc worked as expected. In my case the controls flow ended up something like this:
page_load - load control a
(do something which causes postback and event x to fire)
page_load - make sure you load control a
event_x - clear control a, load control b
(do something which causes postback)
page_load - make sure you load control b
...
it meant loading controls you fully intented discarding, but was the only way I could find to not corrupt the viewstate...
If you have a page with PlaceHolder1 and Label1 in it, then the following code causes the button click event to fire just fine:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicButton = new Button() { Text = "Click me" };
dynamicButton.Click +=new EventHandler(dynamicButton_Click);
PlaceHolder1.Controls.Add(dynamicButton);
}
void dynamicButton_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked button";
}
Behaves the same with a user control:
WebUserControl ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
WebUserControl code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked Button";
}
parent control that loads the child control:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicControl = Page.LoadControl("~/WebUserControl.ascx");
PlaceHolder1.Controls.Add(dynamicControl);
}
Just FYI the issue had to do with validation; the events weren't firing properly because some of the validation controls (there were a ton) weren't configured to only apply to that control.
I'm using a Sharepoint WebPart to load a UserControl which has a button that does some processing on PostBack. I got a problem: when I click the button for the first time, the data loaded on ! IsPosback gets lost, but this does not occur when I click the button again. I think my problem is explained here: Sharepoint Lifecycle, but I haven't been able to find a workaround.
Any help would be really appreciated.
Additional Info:
I'm using EnsureChildControls on the WebPart's OnLoad event, and loading the UserControl on CreateChildControls.
I was able to fix this by programatically specifying an ID to the User Control.
E.g.:
protected void Page_Load(object sender, EventArgs e)
{
this.ID = "MyUserControlID";
}
More info here: http://bytes.com/topic/asp-net/answers/314816-dynamically-loaded-control-event-only-reached-2nd-postback
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (ViewState["MyStuff"] == null)
LoadMyStuffAndSaveToViewState();
else
DoSomethingWith(ViewState["MyStuff"]);
}
I'm using DotNetNuke 4.9.2 and am running into an odd issue.
I have a MultiView in the module that I'm developing, and in one of the views have a GridView that is bound to an ObjectDataSource.
In a separate view, i have several buttons that will switch the SelectMethod of the ObjectDataSource in the 2nd view and then set that view active. That all works fine, until the grid is sorted on the 2nd view - which causes a postback and the ODS somehow picks up its original SelectMethod. The SelectParameters that are assigned at the same time in the code-behind stick though.
Seems to me that the ObjectDataSource should be remembering the SelectMethod in viewstate, shouldn't it?
<asp:ObjectDataSource runat="server" ID="MyObjectDataSource" SelectMethod="MyFirstSelectMethod" TypeName="Whatever"></asp:ObjectDataSource>
protected void Button1_Click(object sender, EventArgs e)
{
MyObjectDataSource.SelectMethod = "MyNewMethod";
// more code here to change the parameters as well...
MyMultiView.SetActiveView(MyView2);
}
When I run that button click, the grid displays as expected. When I click on one of the column headers for the GridView and break in the page load to inspect the SelectMethod, it has reverted to the one declared in the markup.
Any suggestions as to what my problem could be here?
I'm guessing you've made sure that you're not resetting .SelectMethod when the page reloads?
I ended up working around the issue by just using a page property to hold the selectmethod, and then resetting it on each postback...
protected string MySelectMethod
{
get
{
return (string)ViewState["MySelectMethod"] ?? MySearchResultsDataSource.SelectMethod;
}
set
{
ViewState["MySelectMethod"] = value;
MySearchResultsDataSource.SelectMethod = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
MySearchResultsDataSource.SelectMethod = MySelectMethod;
}
}
protected void MyButton_Click(object sender, EventArgs e)
{
MySelectMethod = "MyNewMethod";
}
Still not sure why that SelectMethod prop doesn't stick on a postback in nuke. I'm sure this has worked fine for me in straight asp.net projects in the past...