I'm loading an user control in one of the class file. This is not code behind page. This is common class for grid view which is applied to all the gridviews in all pages.
I added onclick method to the controls in the user control, but they are not firing in the code behind of that user control.
I kept break points. However, it is not reaching those break points. In addition, the user control is getting closed after I click on any control which has onclick method. After clicking the entire page is reloading in which the grid view is loaded and because of it i guess user control is disappearing. I used update panel in user control still it is not working. Onclicking the the user control is going inside on_pageload of that user control.
This user control is displayed when an image on each column of grid header is clicked. My code is as follows
User control ASCX:
<asp:LinkButton ID="lnkSortDescending" runat="server"
onclick="lnkSortDescending_Click">
Sort Descending
</asp:LinkButton>
Code Behind:
protected void lnkSortDescending_Click(object sender, EventArgs e)
{
//some code
}
File in which user control is loaded:
protected void btnFilterButton_Click(object sender, ImageClickEventArgs e)
{
int i = 0;
Panel p = new Panel();
Control uc = (Control)Page.LoadControl("~/UserControls/FilterPanel.ascx");
uc.ID = "Filter"+(i++);
p.Controls.Add(uc);
}
Please help me to solve this problem.
Related
I have a page (company.aspx) that when you click a button on the page the button click event (btnShowDeptsUserControl_Click) dynamically creates a user control and adds to a placeholder. The page reloads with the user control displayed. That works fine.
The issue I am having is that when I click the button on the user control itself, the btnEmailDepts_Click event is not fired, but the main page (company.aspx) is reloaded.
I have read that one way to resolve this is to create the dynamic user control in Page_Init, but I am creating the user control from the main page button click. Also, I am not declaring the user control in the code behind of the main page as you would normally, but do have a placehoder within which the user control is added.
I have also read that you can add a delegate to the main page for the user control button click, but the example seemed to have so much necessary code for such a simple thing that I figured there must be a better way.
Here are the relevant code snippets:
company.aspx:
<asp:Button id="btnShowDeptsUserControl" runat="server" OnClick="btnShowDeptsUserControl_Click">Show Depts</asp:Button>
<asp:PlaceHolder ID="phUserControls" runat="server"></asp:PlaceHolder>
company.aspx.cs:
protected void btnShowDeptsUserControl_Click(object sender, EventArgs e)
{
CreateDeptsUserControl();
}
private void CreateDeptsUserControl()
{
phUserControls.Controls.Clear();
var uc = (UserControl)LoadControl("~/controls/ucDepartments.ascx");
phUserControls.Controls.Add(uc);
}
ucDepartments.ascx:
<asp:Button ID="btnEmailDepts" runat="server" Text="Send Email" OnClick="btnEmailDepts_Click" />
ucDepartments.ascx.cs:
protected void btnEmailDepts_Click(object sender, EventArgs e)
{
EmailDepts(); // breakpoint here is never hit
}
private void EmailDepts()
{
// do something
}
If you read the MSDN, you will notice:
However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.
You are adding your control in the click event which happens after both init and load events, so the postback will not work.
You can call your CreateDeptsUserControl function in the ini event, but there you will have to detect if the btnShowDeptsUserControl was clicked by yourself. It's not hard, you will need to check the submitted values collection and see if there is an item for btnShowDeptsUserControl.
Just wanted to post what I did to make this work. Racil Hilan's answer helped me to arrive at this solution. I did away with the dynamic user control, and went with the more common declared user control in the aspx, but set it to Visible="False" by default.
Notice that the main page button event is empty. Also notice that the user control Page_Load event is empty. All the checking is done in the user control OnInit event, which is executed with each main page load.
In the user control OnInit event I have a couple guard conditions that check to see what EVENTTARGET, if any, caused the page / user control to load. If the EVENTTARGET (control ID) is that of the main page button, then execution will continue and will call LoadSomeData() as well as set the user control Visible = true. Otherwise, if either guard condition evaluates as false, we exit and the user control does not get loaded, so no wasted db / service calls.
company.aspx:
<asp:Button id="btnShowDeptsUserControl" runat="server" OnClick="btnShowDeptsUserControl_Click">Show Depts</asp:Button>
<uc1:ucDepartments ID="ucDepartments" runat="server" Visible="False" />
company.aspx.cs:
protected void btnShowDeptsUserControl_Click(object sender, EventArgs e)
{
// empty, just need the event for inspection later in user control OnInit event.
}
ucDepartments.ascx:
<asp:Button ID="btnEmailDepts" runat="server" Text="Send Email" OnClick="btnEmailDepts_Click" />
ucDepartments.ascx.cs:
protected override void OnInit(EventArgs e)
{
if (string.IsNullOrWhiteSpace(Request.Params["__EVENTTARGET"]))
return;
var controlName = Request.Params["__EVENTTARGET"];
if (controlName != "btnShowDeptsUserControl")
return;
LoadSomeData(); // call method to load the user control
this.Visible = true;
}
protected void Page_Load(object sender, EventArgs e)
{
// empty
}
private void LoadSomeData()
{
// get data from database
// load table / gridview / etc
// make service call
}
protected void btnEmailDepts_Click(object sender, EventArgs e)
{
EmailDepts(); // this event is now executed when the button is clicked
}
private void EmailDepts()
{
// do something
}
Variation that includes jquery to scroll to user control after postback:
In the main page button click event you can also do something like set a hidden var to a value that can be inspected on main page doc ready to do some jquery stuff, such as scrolling the user control into view if it is far down the page (which I am actually doing in my current task).
Not only will this scroll the now loaded user control into view after clicking the main page button, but notice the code in setupDepts(). I hide the asp button that does a postback to load the user control, and show a regular html button. They both look the same (both say Show Depts), but the regular html button, when clicked, will fire jquery to toggle the div that contains the user control to close, click again, it will open, click again it will close, etc.
This is so that you only load the user control once (make db / service calls once) when the main page button is clicked, and then can toggle show or hide it with subsequent clicks of the alternate button. This approach can be used with multiple buttons or links so long as they all have the same class ids. For example, you may have a Show Depts button / link at top of page and another at the bottom of the page, which is the case in my current task.
company.aspx:
<asp:Button id="btnShowDeptsUserControl" runat="server" class="btnShowDepts" OnClick="btnShowDeptsUserControl_Click">Show Depts</asp:Button>
<button class="btnToggleDepts" style="display: none;">Show Depts</button>
<div id="divShowDepts" style="display: none;">
<asp:HiddenField runat="server" id="hdnShowDepts"/>
<uc1:ucDepartments ID="ucDepartments" runat="server" Visible="False" />
</div>
<script language="javascript" type="text/javascript">
$(function () {
toggleDeptsUserControl();
if ($('#<%=hdnShowDepts.ClientID%>').val() === "show")
setupDepts();
});
function setupDepts() {
$('.btnShowDeptsUserControl').hide();
$('.btnToggleDeptsUserControl').show();
scrollToDepts();
}
function scrollToDepts() {
$('#divShowDepts').toggle(700, function () {
if ($(this).is(":visible")) {
$('html, body').animate({ scrollTop: ($(this).offset().top) }, 'slow');
}
});
}
function toggleDeptsUserControl() {
$('.btnToggleDeptsUserControl').on('click', function (event) {
event.preventDefault();
scrollToDepts();
});
}
</script>
company.aspx.cs:
protected void btnShowDeptsUserControl_Click(object sender, EventArgs e)
{
hdnShowDepts.Value = "show";
}
I currently have a master page that has a drop down menu which displays a different User control depending on the menu choice.
Inside of the User control I'm trying to add a submit button that processes the inputted forms inside the user controls using the "_Click()" event handler. My user control aspx looks like the following:
<asp:Button ID="configBttn" runat="server" OnClick="configBttn_Click" AutoEventWireUp="true" />
and then I have the following in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void configBttn_Click(object sender, EventArgs e)
{
Response.Write("Hello world");
}
I have even tried to add an event handler:
configBttn.Click += new EventHandler(configBttn_Click)
However this is still not allowing for the button to be triggered. Any ideas?
I add the user control inside the codebehind inside a div container:
divContainer.Controls.Add(pPage.LoadControl("~/Controls/Control.ascx"));
Where are you creating the UserControl in the Page Lifecycle?
I suspect that it needs to be created in the Init method of its container page.
In addition, they should not be wrapped in a !IsPostback block, or else when the page posts back, the control event handler is not mapped, so nothing is there to catch the click event.
Without seeing the code that adds the user control, I'm guessing that it is not saved as part of the page's view state. Which means when you click the button inside the user control the whole page gets refreshed and the user control is either not created or a different instance of it is created.
Within a tabcontainer I wish to show a variety of tabs which will contain different user controls.
I need to assign the user controls to the tabs through code, and not assign the user controls as its usually done within the tags, for instance:
<ajaxToolkit:TabPanel runat="server" HeaderText="NOMBRE" ID="TabPanel1" Enabled ="true" >
<ContentTemplate>
</ContentTemplate>
</ajaxToolkit:TabPanel>
For what I need this does not work.
So here is my code to assign the tabs to the user controls, the code is as the fallowing:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Control ctrlNombre = LoadControl("~/UserCtrl/Nombre.ascx"); //user control
TabPanel1.Controls.Add(ctrlNombre); //add user control to tabpanel
}
}
And the event “onactivetabchanged” I create a menu depending on which tab is active, which will load the control, here is the code:
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
{
switch(TabContainer1.ActiveTabIndex)
{
case 0:
Control ctrl1 = LoadControl("~/UserCtrl/userControl1.ascx");
TabPanel1.Controls.Add(ctrlNombre);
break;
case 1:
Control ctrl2 = LoadControl("~/UserCtrl/ userControl2.ascx");
TabPanel1.Controls.Add(ctrlApPaterno);
}
}
However, this actually does work, the problem occurs when I clicked a certain button from some user control, this makes a full post back to the server as it would normally will do, but this post back causes the user control previously loaded disappear. What can I do to solve this? I really hope someone will help me out on this one, I will really appreciate it.
Here is an image of what happens when I clicked a button:
Thank you so much guys, I hope someone can help me solve this.
You may need to recreate the tab panels when the postback occurs in the Page_init because the tabpanels do not exist on post backs until they have been made...
So in Page_init you should call a function that makes the default tab collection and then later on the page you can add a new tab panel to the collection.
protected void Page_Init(object sender, EventArgs e)
{
Control ctrlNombre = LoadControl("~/UserCtrl/Nombre.ascx"); //user control
TabPanel1.Controls.Add(ctrlNombre); //add user control to tabpanel
}
Refer:
http://dorababu-meka.blogspot.com/2012/12/create-dynamical-ajax-tab-and-filling.html
http://www.c-sharpcorner.com/uploadfile/Ravish001/create-dynamic-tabs-using-ajax-tab-container-add-controls-read-them-dynamically/
Hope this makes sense.
I am currently building a tab control with multiple tab panels, and would like to have one of the tabs as a button instead of a template with content. The idea being that when the user clicks on the tab with the button, an event would fire and a C# method would run, and the page would post back.
How would I go about doing this? Preferably this could be something generated in the code behind as all the other tabs are programmatically generated along with the content.
You can handle TabContainer's ActiveTabChanged event. Therefore you need to set AutoPostBack for the TabContainer to true.
<asp:TabContainer ID="TabContainer1" runat="server" AutoPostBack="true" OnActiveTabChanged="ActiveTabChanged">
Codebehind:
protected void ActiveTabChanged(object sender, EventArgs e)
{
if (TabContainer1.ActiveTabIndex == 0)
{
// ...
}
// ...
}
I have simply created a user control in asp.net which has a textbox,calendar and a button.
On the click event of that button i am making the calendar visible,and on the calendar's onselectionchanged event i am passing the selected date to the textbox.
Now i have a .aspx page in which i am adding this user control at RUN TIME.
The user control gets added,but the click event of the button by which i am making the calendar visible is not getting fired.
What is the Issue? Its working fine when i add that user control at design time.
But when i add it at run time in not working.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Dates.ascx.cs" Inherits="Date"%>
//created a public object named 'users' of control class
public partial class View_now : System.Web.UI.Page
{
public Control users;
}
//loaded the user control in page load event
protected void Page_Load(object sender, EventArgs e)
{
users = LoadControl("~\\Dates.ascx");
}
//applied the user control to a panel
protected void Button2_Click(object sender, EventArgs e)
{
Panel2.Controls.Add(users);
}
Now when i click the usercontrol's button,the click event doesn't fire.
Add the controls during Page_Init() not Page_Load(). That should do the trick.