Assign an event to a custom control inside a Repeater control - c#

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
}

Related

How To Pass Textbox Value Present In UserControl To Aspx Page Label By Clicking Button In UserControl

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.

ASP.NET Button event is not raised in Web User Control

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.

remove eventhandler on ItemTemplate

I want to remove the event handler of an ItemTemplate in asp .net. Here is the asp code
<ItemTemplate>
<asp:RadioButton runat="server" ID="rdbAnswer" GroupName="Group" AutoPostBack="True"
OnCheckedChanged="rdbAnswer_CheckedChanged" />
</ItemTemplate>
I want to remove the checkedchanged event on code behind. How can i do this ?
Use -= to remove an event handler. You could do that in RowCreated:
protected void gridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
RadioButton rdbAnswer = (RadioButton)e.Row.FindControl("rdbAnswer");
if(YourCondition)
{
// Remove event handler
rdbAnswer.CheckedChanged -= new EventHandler(rdbAnswer_CheckedChanged);
// maybe you also want to set rdbAnswer.AutoPostBack="false" to prevent the postback
}
}
}
Remember to register the RowCreated event handler:
<asp:GridView ID="gridView1" OnRowCreated="gridView1_RowCreated" runat="server">

how to make a Image-button in the user control execute code in the defaultpage.aspx?

1-I have three user controls.
2-I added them to AJAX TabContainer on my default.aspx page
<asp:TabContainer ID="TabContainer1" runat="server">
<asp:TabPanel runat="server" ID="GroupOne">
<HeaderTemplate>
1
</HeaderTemplate>
<ContentTemplate>
<SUR:GroupOne ID="group1" runat="server" />
</ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="GroupTwo" runat="server">
<HeaderTemplate>
2
</HeaderTemplate>
<ContentTemplate>
<SUR:GroupTwo is="group2" runat="server" />
</ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="GroupThree" runat="server">
<HeaderTemplate>
3
</HeaderTemplate>
<ContentTemplate>
<SUR:GroupThree ID="grup3" runat="server" />
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
3- in the first user control i have image-button
<asp:ImageButton ID="ImageButton1" runat="server" />
4- I have this code in my default.vb
Public Sub movit()
GroupThree.Enabled = True
TabContainer1.ActiveTab = GroupThree
End Sub
so how can i execute that sub when i click on the image button in the user-control??
I believe you need to use a delegate to achive this. You can try followings
In your ascx.cs or vb file Add a delegate inside the namespace but outside the UserControl class.
public delegate void ImageButtonClickEventHandler(Object sender, EventArgs args);
Inside UserControl class add an event using delegate.After that call the delegate inside ImageButtonClick event.
public event ImageButtonClickEventHandler ImageButtonClickEvent;
private void imageButton_Click(object sender, System.EventArgs e)
{
if(ImageButtonClickEvent!= null)
{
ImageButtonClickEvent(sender,e);
}
}
In your aspx page add this inside page load event.
UserControl1.ImageButtonClickEvent+=new ImageButtonClickEventHandler(UserControl1_ImageButtonClickEvent);
Finally declare UserControl1_ImageButtonClickEvent function
private void UserControl1_ImageButtonClickEvent(Object sender, EventArgs args)
{
//Call your methods
}
From your designer, double-click the button, this will wire up an event-handler (ImageButton1_Click) and set the onclick property of your imagebutton to ImageButton1_Click.
In the code behind of your page, just call movit() from the generated eventhandler.
[Edit]
Didn't see that the image button was in a user control.
The way to go would be to add an Event to your user control. Raise it when the user clicks the imagebutton. In the page, handle the new event of the user control and call the movit() function.
What aboiut..
1) add an event handler to the user control
public event EventHandler Click
{
add
{
ImageButton1.Click += value;
}
remove
{
ImageButton1.Click -= value;
}
}
2) subscribe to this event from the page you are using the control - default.aspx
<user:control runat="server" ID="uc" OnClick="uc_OnClick" />
and
protected void uc_OnClick(object sender, EventArgs e)
{
movit();
}

ASP.NET Panel FindControl within DataList to change property C#

I'm new to this ASP.NET stuff. In my page I have a Datalist with a FooterTemplate. In the footer I have a couple panels that will be visible depending on the QueryString. The problem I am having is trying to find these panels on Page_Load to change the Visible Property. Is there a way to find this control in the Page_Load? For example this is part of the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DataList ID="dlRecords" runat="server">
<FooterTemplate>
<asp:Panel ID="pnlArticleHeader" runat="server" Visible="false" >
</asp:Panel>
</FooterTemplate>
</asp:Datalist>
</asp:Content>
Here is something in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
location = Request.QueryString["location"];
if (location == "HERE")
{
Panel pnlAH = *Need to find control here*;
pnlAH.Visible=true;
}
}
Like I said I am new at this. Everything I have found doesn't seem to work so I decided to post a specific question. Thanks in advance
DataList has event OnItemCreated, overriding allows select type of row:
Panel _pnlArticleHeader;
void Item_Created(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
_pnlArticleHeader =(Panel)e.Item.FindControl("pnlArticleHeader");
}
}
After event invocation in the field: _pnlArticleHeader you will get desired panel. This way is safe since created only once. NOTE! same way for common DataList's row would return only last one.

Categories