I have a ASP.NET user control, which contains a Telerik Report Viewer plus a button (server control).
I need to handle some stuff inside the click event of the button, but the event does not seem to fire.
Does anyone know why this is the case?
Here is the HTML directives inside the UserControl:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ReportControl.ascx.cs" Inherits="TelerikReportCustomRetrive.UserControl.ReportControl" %>
Here is the markup inside the UserControl:
<form runat="server" id="form1">
<telerik:ReportViewer ID="ReportViewer1" runat="server" Height="461px" ShowDocumentMapButton="False" ShowHistoryButtons="False" ShowNavigationGroup="False" ShowParametersButton="False" ShowPrintPreviewButton="False"></telerik:ReportViewer>
<asp:Button runat="server" ID="btnNav" OnClick="btnNav_Click" />
And the code behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var instanceReportSource = new InstanceReportSource
{
ReportDocument =
new TheReport()
};
ReportViewer1.ReportSource = instanceReportSource;
}
}
protected void btnNav_Click(object sender, EventArgs e)
{
Response.Write("Button Fired!");
}
Delete the if(!PostBack) statement. You should always initialize the control, not only if page is not post back.
Related
I have a master page. In the master page I have a UserControl for the footer. In the footer I have a button that is not firing OnClick. During debugging I see the function being called by OnClick, btnSignup_Click, is not getting hit. I can't seem to figure out where the mistake in my code is.
Also I wanted to note that the validation functionality is working correctly.
master.master
<%# Master Language="C#" AutoEventWireup="true" Inherits="master" Codebehind="master.master.cs" %>
<%# Register TagPrefix="xyz" TagName="Footer" Src="~/controls/footer.ascx" %>
<xyz:Footer ID="Footer" runat="server" />
footer.ascx
<%# Control Language="C#" AutoEventWireup="true" Inherits="footer" Codebehind="footer.ascx.cs" %>
<div>
<asp:TextBox ID="fName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorfName" ValidationGroup="validationSignup" Display="Static" ControlToValidate="fName" ErrorMessage="First Name required" runat="server"></asp:RequiredFieldValidator>
</div>
<div class="button">
<asp:Button ID="btnSignup" CommandName="Button" runat="server" ValidationGroup="validationSignup" Text="Signup" HeaderText="Please fill in all required fields before continuing." OnClick="btnSignup_Click"/>
</div>
<div class="validationSummary">
<asp:ValidationSummary ID="ValidationSummary" ValidationGroup="validationSignup" runat="server"></asp:ValidationSummary>
</div>
footer.ascx.cs
public partial class templates_site_footer : BaseUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
btnSignup.Click += new EventHandler(btnSignup_Click);
}
protected void btnSignup_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
// code to execute after button is clicked
}
}
Remove btnSignup.Click += new EventHandler(btnSignup_Click); code from Page_Load event, You had already assigned OnClick event to button in .ASCX markup and no need to check validate of your page again in btnSignup_Click, you can directly write button click event code which you want to execute.
Your Footer User Control Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
//btnSignup.Click += new EventHandler(btnSignup_Click);
}
protected void btnSignup_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// code to execute after button is clicked
}
else
{
// Your page does not validated.
}
}
TestUC.ascx Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
Test.aspx Page Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
OutPut:
I Need ..
Step1: Enter Some text In Text Box
Step2:Then I Click Click Button
[Note: This Two Controls Are Bind From UserControl]
Step3:What Text Entered in TextBox Is Show In label [Note Label Present In Aspx Page]
You will need to have a custom event & you will also need to expose the Text property of the TextBox in your UserControl, like this.
public partial class YourUserControl : UserControl
{
public String Text
{
get
{
return this.txtBox1.Text;
}
//write the setter property if you would like to set the text
//of the TextBox from your aspx page
//set
//{
// this.txtBox1.Text = value;
//}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event TextAppliedEventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
//Taking a local copy of the event,
//as events can be subscribed/unsubscribed asynchronously.
//If that happens after the below null check then
//NullReferenceException will be thrown
TextAppliedEventHandler handler = TextApplied;
//Checking if the event has been subscribed or not...
if (handler != null)
handler(this, e);
}
protected void yourUserControlButton_Click(Object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Then in your aspx page, where you have placed YourUserControl (OR you are dynamically adding it from the code behind), you can subscribe to this event like this.
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
yourUserControl.TextApplied += new YourUserControl.TextAppliedEventHandler(yourUserControl_TextApplied)
}
}
You can use the custom event of the user control in your page like this.
protected void yourUserControl_TextApplied(Object sender, EventArgs e)
{
yourLabelInYourPage.Text = yourUserControl.Text;
}
And you are done...
EDIT : You can rename the Controls & Events as you like. I have used the names only for the example purpose.
EDIT : In website projects, if you want to add your user control dynamically then,
you might need to include the namespace ASP in your page, like this.
using ASP;
And add this Directive in your page in the aspx markup.
<%# Reference Control="~/PathToYourUserControl/YourUserControl.ascx" %>
other solution : create an event in the usercontrol, which is called in the button click.
Subscribe to this event in the codebehind of the aspx page. that way you can update your interface only if a value is provided.
a little more complicated, but you could re-use this logic to more complex control / parent control feature in the future.
i can add code snippet if asked
This Answer Is Prepared By Help Of #Devraj Gadhavi i Edited Some Code .
UserControl Page Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
UserControl Page Code
public partial class TestUC : System.Web.UI.UserControl
{
public String Text
{
get
{
return this.txtbox1.Text;
}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event EventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
if (TextApplied != null)
TextApplied(this, e);
}
protected void btn1_Click(object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Aspx Page Design Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
Aspx Cs File Code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ucTest.TextApplied += new EventHandler(ucTest_TextApplied);
}
protected void ucTest_TextApplied(Object sender, EventArgs e)
{
lbl1.Text = ucTest.Text;
}
}
Another method ,If you don't want to expose the Text property of the TextBox in your UserControl Just use method "UserControl.FindControl("Id Of your Textbox which is present in user control")" in your Case WebUserControlTest.FindControl("txtbox1").
And below is the simpler way to register an event handler on the parent web form's code behind.
Code goes as below for parent form asxp.cs
protected override void OnInit(EventArgs e)
{
//find the button control within the user control
Button button = (Button)WebUserControlTest.FindControl("btn1");
//wire up event handler
button.Click += new EventHandler(button_Click);
base.OnInit(e);
}
void button_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox) WebUserControlTest.FindControl("txtbox1");
//id of lable which is present in the parent webform
lblParentForm.Text=txt.text;
}
Also, you can achieve this using JavaScript like below (given your code above):
<script type="text/javascript">
function getUCTextboxValue() {
let txtName = document.getElementById('<%=ucTest.FindControl("txtbox1").ClientID %>');
let lbl = document.getElementById('<%=lbl1.ClientID %>');
lbl.innerText = txtName.value
}
Also, from the parent page, you can add a HiddenField and save the textbox value on it (using the JavaScript code above) then catch its value from code behind.
I have save button on a dynamic usercontrol that I load onto aspx page, but I want to move the button onto .aspx page instead. How can I fire the onclick event from aspx to ascx.
Any help would be great.
Cheers.
Code Example:
ascx:
protected void BT_Save_Click(object sender, EventArgs e)
{//Save details currently on ascx page }
aspx:
protected void BT_aspx_Click(object sender, EventArgs e)
{
//when this button is clicked I need it to fire BT_Save_Click on ascx page to save the data
}
In user control
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
In User control .cs page
public event EventHandler ButtonClickDemo;
protected void Button1_Click(object sender, EventArgs e)
{
ButtonClickDemo(sender, e);
}
In Page aspx page
<uc1:WebUserControl runat="server" id="WebUserControl" />
In Page.cs
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl.ButtonClickDemo += new EventHandler(Demo1_ButtonClickDemo);
}
protected void Demo1_ButtonClickDemo(object sender, EventArgs e)
{
Response.Write("It's working");
}
Write a public / internal sub on the ASCX, and then call it from the onClick on the ASPX?
You'll need to create a custom event on your ascx user control and subscribe it within your aspx page.
have a look at this question
define Custom Event for WebControl in asp.net
this.Controls.Add(new CheckBox{ Checked = true; })
When I add this in the page_load. It works, it adds the checkbox and it is visible.
A little different approach:
var button = new CheckBox{ Checked = true; }
globals.button = button;
this.Controls.Add(button);
Globals is a class with a checkbox property on which I want to set the checkbox in the hope of retrieving it's a data after pressing a button.
public static CheckBox button { get; set; }
However, when a button is pressed, the control has vanished of my screen and the button in my globals class has not been updated with any changes I have made to the checkbox.
How can I change the checked state of a checkbox and catch it's current state when I perform a button.click event?
You must re-create dynamic controls on every postback, they wont magically re-appear because every request is a new instance of the Page class.
See my previous post on this subject, it is using a user control but the idea is just the same.
And another
You must add the control before Page_Load
I normally do it in the overridden CreateChildControls but some people use Page_Init.
see this article
Update
This is a very simple way to add the checkbox dynamically, that preserves state/value when the button is clicked.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="ph"></asp:PlaceHolder>
<asp:Button OnClick="btn_Click" runat="server" ID="btn" Text="Click Me" />
<asp:Label runat="server" ID="lbl"></asp:Label>
</form>
</body>
</html>
Then Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test : Page
{
private CheckBox MyCheckBox { get; set; }
protected override void CreateChildControls()
{
this.MyCheckBox = new CheckBox() { Checked = true };
this.ph.Controls.Add(this.MyCheckBox);
base.CreateChildControls();
}
protected void btn_Click(object sender, EventArgs e)
{
var someValue = this.MyCheckBox.Checked;
this.lbl.Text = someValue ? "Checked" : "Not Checked";
}
}
If dynamic controls are created in the Page_Load(object sender, EventArgs e) method they will not return the changes the user made.
The reason you're having problems is the ASP.Net view state is created before the Page_Load(object sender, EventArgs e) method is called. The ASP.Net view state hold what controls are on the page and their values. The Page_Init(object sender, EventArgs e) method is called before the ASP.Net view state is created. By creating the controls in the Page_Init(object sender, EventArgs e) method will return what the user enter, furthermore the controls will only need to be created if the page isn't a post back.
If you can't create the controls in the Page_Init(object sender, EventArgs e) method for some reason, you will edit to change the ASP.Net view state the Page_Load(object sender, EventArgs e).
If you need to create the controls in the Page_Load(object sender, EventArgs e) method this question should help How to Persist Variable on Postback
I have a Repeater control which in some of its cells contains a UserControl which contains a DropDownList. On the ItemDataBound event of the Repeater control I'm assigning an event to the DropDownList like so:
protected void MyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
...
MyControl myControl = (MyControl)e.Item.FindControl("MyControl01");
myControl.DataSource = myObject;
myControl.DataBind();
myControl.DropDownList.SelectedItemChange += MyMethod_SelectedIndexChanged;
myControl.DropDownList.AutoPostBack = true;
....
}
protected void MyMethod_SelectedIndexChanged(object sender, EventArgs e)
{
//Do something.
}
The event never fires. Please I need help.
Your event is not being raised in a PostBack because your event handler has not been attached (it is only attached during the iteration of the page life-cycle when your repeater is databound).
If you attach your event handler declaratively in the markup such as:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
</ItemTemplate>
</asp:Repeater>
Then your event handler will be called during PostBacks.
There are two things you can try to see if it will help:
Try binding your MyRepeater on every page request, not just when !IsPostBack.
Bind MyRepeater inside OnInit.
For 1) If your dynamically created controls are created the first time the page loads and then again when postback occurs, ASP.NET will notice that the event raised matches and will fire the event.
For 2) The designer used always place event attachment in OnInit, though it should work fine in OnLoad too.
First make sure your databinding is not resetting your dropdowns.
Here is the code for the control which will nest inside the repeater ItemTemplate
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ListBoxContainer.ascx.cs" Inherits="OAAF.Common.ListBoxContainer" %>
<asp:ListBox ID="lstFromControl" runat="server" Rows="1" DataTextField="Text" DataValueField="Id" OnSelectedIndexChanged="LstFromControl_SelectedIndexChanged" AutoPostBack="true" />
The code behind for the control which will nest inside the repeater ItemTemplate
public partial class ListBoxContainer : System.Web.UI.UserControl
{
//declare the event using EventHandler<T>
public event EventHandler<EventArgs> ListBox_SelectedIndexChanged;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LstFromControl_SelectedIndexChanged(object sender, EventArgs e)
{
//fire event: the check for null sees if the delegate is subscribed to
if (ListBox_SelectedIndexChanged != null)
{
ListBox_SelectedIndexChanged(sender, e);
}
}
}
Note that this above control uses the listbox change event internally, then fires an event of its own: ListBox_SelectedIndexChanged. You could create custom event args here as well, but this uses the standard EventArgs.
Your repeater which has the control may look like this
<asp:Repeater ID="rptTest" runat="server">
<ItemTemplate>
<br />
<ctrl:wucListBox ID="listBoxControl" runat="server" OnListBox_SelectedIndexChanged="ListBoxControl_SelectedIndexChanged" />
</ItemTemplate>
</asp:Repeater>
Register the control at the top of the page the repeater is on, for example
<%# Register Src="~/Common/ListBoxContainer.ascx" TagName="wucListBox" TagPrefix="ctrl" %>
It handles the event ListBox_SelectedIndexChanged, and the method which handles this is in the code behind of the page the repeater sits on.
protected void ListBoxControl_SelectedIndexChanged(object sender, EventArgs e)
{
//some code
}