OnServerClick for button not working - c#

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;
}
}

Related

Setting Button in listview Visibility to False if query result is "0"

I am building a web application in ASP.net and I have a little problem.
I have a LISTVIEW to display data from a data source, and in that listview I have included a BUTTON in every row to be visible if the result of the query in the Page_load is 0.
The Query works, but I don't know how to select the button in the query.
I have tried
ListView1.FindControl("hiddenButton").visible = false;
this is the buttons code
<asp:Button ID="hiddenButton" runat="server" CommandArgument ='<%# Eval("ProfileId") %>' Text="Add Friend" CssClass="btn btn-info pull-right" OnClick="addFriend_Click" Width="105px" allign="right"/>
But its not working.
You can do this in ItemDataBound event:-
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType==ListViewItemType.DataItem)
{
if (YourCondition)
{
Button hdn = (Button)e.Item.FindControl("hiddenButton");
hdn.Visible = false;
}
}
}
You need to associate this event handler in your mark-up(if not already done):-
<asp:ListView ID="ListView1" OnItemDataBound="ListView1_ItemDataBound">
</asp:ListView>
You can use ItemDataBound event To set Buttons visible to True/False
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Button hiddenButton=(Button) dataItem.FindControl("hiddenButton");
hiddenButton.Visible = false;
}
}

ImageButton open link in new page within Repeater

I have the below Image Button which resides in a Repeater:
<asp:ImageButton PostBackUrl='<%# DataBinder.Eval(Container.DataItem, "VesselId", "getattachment.do?VesselId={0}") %>' CausesValidation="false" ID="insurancestatus" runat="server"/>
So every time the user clicked on the button they were shown their attachment.
The requirement has since changed, and the attachment must open on a new page so I added the following to the Repeaters ItemDataBound event:
ImageButton imagebuttonInsurance = (ImageButton)e.Item.FindControl("insuranceStatus");
imagebuttonInsurance.OnClientClick = String.Format("aspnetForm.target = '_blank'; return true()");
Now when I click on the image it does open another page but it just reloads the previous page on the new page. I tried removing the PostBackUrl and wiring up the following click event:
protected void insurancestatus_Click(object sender, ImageClickEventArgs e)
{
Vessel vessel = (Vessel)e.Item.DataItem;
Response.Redirect(String.Format("~/Secure/getattachment.do?VesselId={0}", vessel.VesselId));
}
But I couldn't get a handle on the item so cannot use the VesselId for the link, where am I going wrong here?
Use the second method, but use the command argument property like:
<asp:imagebutton runat=server...... commandargument='<%# Eval("vesselid") %>' />
then:
protected void insurancestatus_Click(object sender, ImageClickEventArgs e)
{
string vesselId = ((ImageButton)sender).CommandArgument;
Response.Redirect(String.Format("~/Secure/getattachment.do?VesselId={0}", vesselId));
}

Autopostback prevents button click

I have an asp.net page and on it there are a number of controls, including:
A textbox with autopostback = true and the server side textchanged event implemented
A button with the server side click event implemented
The textbox performs the postback as soon as the user leaves the control (ie, focus is lost). The problem is that if the user happens to change the value and then press the button without leaving the textbox, then on button click the textbox will perform the postback but the button click will be lost.
How can i force both the textbox and the button events to fire consecutively in such cases?
Thanks
Try:
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
CS:
protected void Button1_Click1(object sender, EventArgs e)
{
}
You can delay postback from textbox and cancel it in case of button click. To do this add code below to Page_PreRender method:
protected void Page_PreRender(object sender, EventArgs e)
{
Button1.OnClientClick = string.Format("if(window.{0}Timeout){{ clearTimeout(window.{0}Timeout); }}",
TextBox1.ClientID);
TextBox1.Attributes["onChange"] = string.Format("javascript:window.{0}Timeout = setTimeout(\"{1}\", 500); return;",
TextBox1.ClientID,
ClientScript.GetPostBackEventReference(TextBox1, ""));
}

Identifying object in ItemTemplate and event not firing

I am using a RadListView control with an ItemTemplate that contains a button as shown here:
<ItemTemplate>
<tr class="rlvI">
//more TD elements here
<td>
<telerik:RadButton ID="ENABLEDToggle" runat="server" Width="75" ButtonType="StandardButton" AutoPostBack="true"
ToggleType="CustomToggle" Checked='<%# Enabled_Converter(Eval("ENABLED")) %>' OnCheckedChanged="TaskStateChange_Clicked">
<ToggleStates>
<telerik:RadButtonToggleState Text="Enabled" />
<telerik:RadButtonToggleState Text="Disabled" />
</ToggleStates>
</telerik:RadButton>
</td>
</tr>
</ItemTemplate>
My first question is why is it that when my button is pressed, I do not enter my TaskStateChange_Clicked event handler? It is as if the event is never fired.
Second, whenever a button is clicked, how do I get the object associated with that row?
As for the first question, check how you are binding your RadListView. Problems like this usually appear if controls are bound with data on every postback. So if you have something like
void Page_Load(object sender, EventArgs e)
{
...
RadListView1.DataSource = dataSource;
RadListView1.DataBind();
...
}
replace it with
void Page_Load(object sender, EventArgs e)
{
...
if (!this.IsPostBack)
{
RadListView1.DataSource = dataSource;
RadListView1.DataBind();
}
...
}
Update from comments. Another reason might be that the type of your button is StandardButton while spec implies that event CheckedChanged is fired only when button type is ToggleButton.
As for the second question consider using RadListView's ItemCommand event. This way you can make use of CommandArgument property of RadButton and pass any info you want in it, say object's ID.

Can a userControl event cause an update panel to refresh?

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);
}

Categories

Resources