I have an aspx.
<div id="headerRegion" class="borderDiv">
<xy:paymentHeader id="paymentHeader1" runat="server" />
</div>
<div id="paymentRegion" class="borderDiv">
<asp:UpdatePanel ID="paymentFormUpdater" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="plcPaymentForm" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
on page init, the placeHolder loads an ascx.
private Control GetPaymentControl(char? coverageBenefitPeriod)
{
Control paymentCtl = null;
switch (coverageBenefitPeriod)
{
case 'L':
paymentCtl = this.LoadControl("~/Controls/Lumpform.ascx");
break;
case 'W':
paymentCtl = this.LoadControl("~/Controls/Periodicform.ascx");
break;
default:
paymentCtl = this.LoadControl("~/Controls/Lumpform.ascx");
break;
}
return paymentCtl;
}
plcPaymentForm.Controls.Add(control);
There's a radioButton List on paymentHeader1 control. When I toggle that radio button would like to elegantly swap between Periodicform.ascx and Lumpform.ascx in the placeholder "plcPaymentForm". How do I do this correctly? I am trying not to load both controls and toggle their visibility. If you have any ideas how to do this properly with minimal page interuption please point me in the right direction.
Thanks,
~ck in San Diego
Little different version of what drs9222 had answered.
1. Declare a delegate
Public delegate void UserControlFormSubmit(object sender, EventArgs e);
2. Declare an event inside user control of type UserControlFormSubmit
Public event UserControlFormSubmit OnFormSubmit;
3. Set User control event as trigger for update panel like this
<asp:UpdatePanel ID="paymentFormUpdater" runat="server" UpdateMode=”Conditional” ChildrenAsTriggers=”true”>
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="plcPaymentForm" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="paymentHeader1" EventName="OnFormSubmit" />
4. Raise the event OnFormSubmit when selectedindexchange event occurs for the radioButtonList. (Note that you need to set AutoPostBack=true for radioButtonList as mentioned by drs9222.
I see three quick and dirty ideas:
You could probably set the radio button list to autopostback and then bubble the event up so that xy:paymentHeader could be used as a trigger for the update panel.
Have xy:paymentHeader raise an event and call the updatepanel's Update method in the event handler.
Pass the updatepanel's id into the control and use find control to find the updatpanel and call its update method.
Example (for #1):
UserControl:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = ((RadioButtonList)sender).SelectedValue;
char? c = null;
if (!string.IsNullOrEmpty(value))
{
c = value[0];
}
RaiseBubbleEvent(this, new CommandEventArgs("SelectedIndexChanged", c));
}
Page:
protected override bool OnBubbleEvent(object source, EventArgs args)
{
if (args is CommandEventArgs)
{
CommandEventArgs cArgs = (CommandEventArgs)args;
if (cArgs.CommandName == "SelectedIndexChanged")
{
Control c = GetPaymentControl((char?)cArgs.CommandArgument);
// ...
updatePanel.Update();
return true;
}
}
return base.OnBubbleEvent(source, args);
}
Related
My .aspx:
<asp:LoginView runat="server">
<RoleGroups>
<asp:RoleGroup Roles="admin">
<ContentTemplate>
<asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" />
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
My code-behind
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
string Mystring = String.Format("{0}", /*I want to put Textbox.text here*/ );
}
}
The problem is that I get a "Textbox" is not defined in the current context. I fiddled around a bit and found that removing the loginview restores the functionality that I want. So why does the loginview break my ability to reference across controls that are in the same view?
C# is case sensitive. Instead of the name Textbox (b is in lower case) use TextBox. Also, I recommend you change the ID of your controls to something more meaningful. Do not set the ID of a TextBox to "TextBox"
Further to your comments, you seem to have your TextBox inside a LoginView. The only way I could get access to this control is
Control container = new Control();
LoginView1.RoleGroups[0].ContentTemplate.InstantiateIn(container);
foreach (Control control in container.Controls)
{
if (control.ID == "txtName")
{
//Phew. Got your control
}
}
Note: I have set the LoginView ID to LoginView1 and TextBox ID to txtName
Try this.TextBox! that should solve the Case Sensitivity thing! also... bad variable naming... As a rule of thumb, do not name a variable exactly like the name of a class...
I have an html button and I'd like to have a server side click event but it's not firing when the button is clicked and the page does a postback. The button is inside the ItemTemplate for an <asp:ListView id="usersListView"/> that renders a table of information.
aspx
<button runat="server" id="delete" class="btn btn-mini" title="Delete" OnServerClick="delete_Onclick"></button>
aspx.cs
protected void delete_Onclick(object sender, EventArgs e) {
ListViewItem listViewItem = (ListViewItem)((Button)sender).NamingContainer;
if(listViewItem != null) {
Membership.DeleteUser(((Label) listViewItem.FindControl("userName")).Text);
}
}
My guess is that it will not work like this because events raised by nested controls placed in item templates should rather be handled by ListView's ItemCommand event.
For this to work then, you should set button's CommandName and CommandArgument and handle specific values in the listview's ItemCommand.
However, if I remember correcly, the HtmlInputButton does not have CommandName and CommandArgument properties. Instead, use asp:Button
<asp:Button id="delete" runat="server" CommandName="something" CommandArgument="somethingelse" />
and handle the listview's itemcommand:
protected void usersListView_ItemCommand( object sender, ListViewCommandEventArgs e )
{
switch ( e.CommandName ) {
case "something" :
// this is where you handle the button click
}
}
Note that CommandArgument is usually bound to an item-specific value (id perhaps) so that inside the server-side handler you can precisely identify the exact clicked button:
<asp:Button id="delete" runat="server" CommandName="something" CommandArgument="<%# Eval( "id" ) %>" />
protected void usersListView_ItemCommand( object sender, ListViewCommandEventArgs e )
{
switch ( e.CommandName ) {
case "something" :
// this is where you handle the button click
var itemid = e.CommandArgument;
}
}
I'm building a table of data for price quotes (think table of Stock quotes) which needs to be refreshed every 5 secs. Each row has some data about one Stock in several columns and the last column in each row has a LinkButton to see more info about that particular stock. Everything works but the LinkButton. The entire table is nested inside an UpdatePanel which I think is causing the problem. I've seen a fair number of posts on this topic but none that have worked for me.
Here is my .aspx code:
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:Timer ID="Timer" OnTick="Timer_Tick" runat="server" Interval="5000" />
<div id="itemList">
<asp:UpdatePanel ID="itemPanel" UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server">
<Triggers><asp:AsyncPostBackTrigger ControlID="Timer" /></Triggers>
<ContentTemplate>
<asp:Panel ID="Panel_ItemList" runat="server" width="100%"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
and my .aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!Page.IsPostBack)
{
updateItemsTable();
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
Panel_LoginAlert.Visible = true; // <-- THIS IS NOT FIRING!!
}
protected void Timer_Tick(object sender, EventArgs e)
{
updateItemsTable();
}
protected void updateItemsTable()
{
//... Query my DB
if (rdr.HasRows)
{
Panel_ItemList.Controls.Add(new LiteralControl("<!-- ItemList Panel -->\n"));
while (rdr.Read())
{
LinkButton lb = new LinkButton();
lb.Text = "Item";
lb.ID = "lbItem_" + strDBitemID;
lb.CommandName = strDBitemName;
lb.CommandArgument = strDBitemID;
lb.Command += new CommandEventHandler(LinkButton_Click);
Panel_ItemList.Controls.Add(lb);
}
Panel_ItemList.Controls.Add(new LiteralControl("<!-- END ItemList Panel -->\n"));
}
//...
conn.Close();
}
So the page loads fine and the timer reloads the table fine, but the LinkButtons do not fire the CommandEventHandler. This works fine if I remove the Timer.
Things I've tried:
I tried using Buttons rather than LinkButtons but this didn't help.
I read dozens of posts saying to add an ID to the LinkButton controls, but this didn't help either.
I believe the problem is when your adding the controls. For this to work the server controls need to be added in the Init event, or overriding OnInit(EventArgs).
Instead of explicitly creating the controls you could replace the panel with a repeater. Then bind your results from the database to the reader.
<asp:Repeater ID="TheRepeater" ...>
<ItemTemplate>
<asp:LinkButton onClick="LinkButton_Click" ...bind values to properties here />
</ItemTemplate>
</asp:Repeater>
code behind
TheRepeater.Visible = rdr.HasRows;
TheRepeater.DataSource = rdr;
TheRepeater.DataBind();
That being said, if all you want to do is alter the UI, that could easily be accomplished with jquery.
I believe the problem is in the page life cycle, since you are creating a dynamic control and adding the event after the page_init or page_load, its not getting hooked up correctly to the control, you could try out the following and see if it works:
Add page init:
protected void Page_Init(object sender, EventArgs e)
{
updateItemsTable();
}
and change the timer tick event to:
protected void Timer_Tick(object sender, EventArgs e)
{
itemPanel.Update();
}
and that should do the trick.
Hope this is of help.
Cheers.
You need to add postback trigger as following:
<asp:PostBackTrigger ControlID="SearchBrn"/>
I am running into a problem with Ajax and C# asp.net. I am using Microsoft Visual Studio 2010.
First let me explain my web page.
I have script manager, and directly underneath that I have a update panel.
This is the dynamic placeholder I've been fiddling with.
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
Within my update panel, I have a dynamic control & a button.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<DBWC:DynamicControlsPlaceholder ID="DynamicControlsPlaceholder1"
runat="server">
</DBWC:DynamicControlsPlaceholder>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Now in my code behind:
I simply add 5 text boxes to a dynamic control. Page load;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["id"] = 0;
int id = (int)ViewState["id"];
for (int i = 0; i < 5; i++)
{
id++;
TextBox txt = new TextBox();
txt.ID = id.ToString();
DynamicControlsPlaceholder1.Controls.Add(txt);
txt.Text = i.ToString();
}
ViewState["id"] = id;
}
}
Now all my button does is add another TextBox to the dynamic control pannel.
protected void Button1_Click(object sender, EventArgs e)
{
int id = (int)ViewState["id"];
TextBox txt = new TextBox();
txt.ID = id.ToString();
DynamicControlsPlaceholder1.Controls.Add(txt);
// DynamicControlsPlaceholder1.DataBind();
txt.Text = id.ToString();
id++;
ViewState["id"] = id;
}
* Note I am using a custom dynamic control panel so their ID's are saved to the next page even though we have them creeated in a !Page.IsPostBack
The problem is that my button event handler only works once. I'm pretty sure its because the Ajax is calling a partial postback and it's not recognizing it to call my button event handler.
I'm not sure, any help is appriciated.
Firebug works wonders for debugging ajax. "There were multiple controls with the same ID '5'."
What a simple fix. Moved id++; to the top of Button1_Click event handler.
If you're ever assuming ajax is breaking your event handler just because the breakpoint is not firing in the event handler, firebug may save you too!
There was absolutely nothing wrong with the event handler, but the code within it was causing an error and ajax wasn't allowing it to break.
I have Created A Custom Control which is a DropDownList with specified Items. I designed AutoPostback and SelectedCategoryId as Properties and SelectedIndexChanged as Event for My Custom Control.
Here Is My ASCX file Behind Code:
private int _selectedCategoryId;
private bool _autoPostback = false;
public event EventHandler SelectedIndexChanged;
public void BindData()
{
//Some Code...
}
protected void Page_Load(object sender, EventArgs e)
{
BindData();
DropDownList1.AutoPostBack = this._autoPostback;
}
public int SelectedCategoryId
{
get
{
return int.Parse(this.DropDownList1.SelectedItem.Value);
}
set
{
this._selectedCategoryId = value;
}
}
public string AutoPostback
{
get
{
return this.DropDownList1.AutoPostBack.ToString();
}
set
{
this._autoPostback = Convert.ToBoolean(value);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedIndexChanged != null)
SelectedIndexChanged(this, EventArgs.Empty);
}
I Want Used Update Panel to Update Textbox Fields According to dorp down list selected index.
this is my code in ASPX page:
<asp:Panel ID="PanelCategory" runat="server">
<p>
Select Product Category:
<myCtrl:CategoryDDL ID="CategoryDDL1" AutoPostback="true" OnSelectedIndexChanged="CategoryIndexChanged"
SelectedCategoryId="0" runat="server" />
</p>
<hr />
</asp:Panel>
<asp:UpdatePanel ID="UpdatePanelEdit" runat="server">
<ContentTemplate>
<%--Some TextBoxes and Other Controls--%>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="CategoryDDL1" />
</Triggers>
</asp:UpdatePanel>
But Always The Selected Index of CategoryDDL1 is 0(Like default). this means Only Zero Value will pass to the event to update textboxes Data. what is the wrong with my code? why the selected Index not Changing? Help?
If your BindData() method is completely self-contained, move that from Page_Load to:
protected override void OnInit(EventArgs e)
{
BindData();
}
This will keep your dropdown list in your control from being rebound on every page load, which I assume is the problem from the code that you've posted.
If, however, your BindData() method requires information from the parent page, change the page load to:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.Page.IsPostback) {
BindData();
}
DropDownList1.AutoPostBack = this._autoPostback;
}
This will allow your dropdown to be bound only on the first page load, and subsequent loads should be able to access the properties correctly.
Also, be sure to check your ASPX page to make sure you're not binding the ASCX control on every page load. This can be resolved in the same way on the parent page.