Call a clientsideevent from another clientsideevent - asp.net

ASP.net(C#), VS2010, Win 7.
New to WebDev, so this might be a simple syntax thing but here it goes...
Long story short I have to force a postback on a GridView that shows attachments I upload using an ASPxUploadControl. I put the GridView inside an ASPxCallbackPanel and am trying to get my GridView to update on the page after an attachment is uploaded using ASPxCallbackPanel.PerformCallback();
Here's the Upload control, in its' ClientSideEvent is where I'm trying to call the clientSideEvent from the Button shown below. Just trying to force a button click really, but I tried doing it from the code-behind but that didn't work. Any help would be appreciated!
<dxuc:ASPxUploadControl ID="FileUpload1" runat="server"
ClientInstanceName="uploader"
ShowAddRemoveButtons="False"
ShowUploadButton="True"
AddUploadButtonsHorizontalPosition="Center"
AddUploadButtonsVerticalPosition="Top" FileInputCount="1"
UploadMode="Advanced"
OnFileUploadComplete="UploadControl_FileUploadComplete"
Size="30">
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.Click; }" />
<%-- <AdvancedModeSettings EnableMultiSelect="True" /> "does not have public property named "advancedModeSettings" version is too old--%>
<ValidationSettings
AllowedFileExtensions=".doc,.pdf,.xls,.txt,.jpeg,.jpg,.gif,.png,.oft,.htm,.html,.mht,.rtf,.zip"
MaxFileSize="5242880"
FileDoesNotExistErrorText="This file can't be found."
GeneralErrorText="Custom file uploading fails due to an external error that doesn't relate to the ASPxUploadControl's functionality"
MaxFileSizeErrorText="Size of the uploaded file exceeds maximum file size">
<ErrorStyle ForeColor="Red"/>
</ValidationSettings>
</dxuc:ASPxUploadControl>
Here is the GridView as well as a button I made that successfully refreshes the grid.
<div>
<dxe:ASPxButton ID="ASPxButton1" runat="server" ClientInstanceName="Button1" Text="Reload Panel" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {ASPxCallbackPanel1.PerformCallback(); e.processOnServer = true;}" />
</dxe:ASPxButton>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel1" runat="server"
ClientInstanceName="ASPxCallbackPanel1" Width="492px"
Height="100%">
<PanelCollection>
<dx:PanelContent runat="server">
<asp:GridView ID="gvAttachment" SkinID="grid" runat="server" Width="98%"
OnRowDataBound="AttachmentControl_OnRowDataBound"
meta:resourcekey="gvAttachResource1"
PagerSettings-FirstPageText="<%$ Resources:CommonControlText,FirstPageText %>"
PagerSettings-LastPageText="<%$ Resources:CommonControlText,LastPageText %>"
PagerSettings-PreviousPageText="<%$ Resources:CommonControlText,PreviousPageText %>"
PagerSettings-NextPageText="<%$ Resources:CommonControlText,NextPageText %>"
AutoGenerateColumns="False">
<EmptyDataRowStyle CssClass="emptyData" />
<EmptyDataTemplate>
<table class="usercontroldetail container_table">
<tr>
<td class="tdlayout">
<asp:Label ID="Localize1" runat="server">
<%= Placeholder %>
</asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="AtchmtId" HeaderText="Attachment ID"
visible = "false" meta:resourcekey="BoundFieldResource1">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField ="FileNm" HeaderText="File Name" />
<asp:BoundField DataField="UsrNm" HeaderText="Uploaded By"
/>
<asp:BoundField DataField="AtchmtDt" HeaderText="Date"
/>
<asp:BoundField DataField="FileSizeCnt" HeaderText="File Size"
/>
<asp:TemplateField AccessibleHeaderText="Actions" HeaderText="Actions">
<ItemTemplate>
<div style="text-align:center;">
<asp:LinkButton ID="btnDelete" Visible="False" runat="server"
ToolTip="Delete Selected Attachment"
OnClick="btnDelete_Click"
Text="Delete" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnDeleteResource1" />
<asp:Label ID="lblPipe" runat="server" Text="|" />
<asp:LinkButton ID="btnView" Visible="False" runat="server"
ToolTip="View Selected Attachment"
OnClick="btnView_Click"
Text="View" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnViewResource1" />
</div>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
</Columns>
<%--<PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next >" PreviousPageText="< Previous"></PagerSettings>--%>
<RowStyle CssClass="row_odd" />
<AlternatingRowStyle CssClass="row_even" />
</asp:GridView>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
FYI: The GridView is getting the new attachment put in it. I'm just not seeing it on the page because the UploadControl only updates itself.
Edit:Figured it out just used the OnClick() method as below. Derp. Forgot that the ASPx button inherited all the ASP buttons methods. But now my original plan of making the button invisible seems to be foiled. When Button1.OnClick() is called with the Visible property for the Button set to "false". it says Button1 is not defined. Anyway around this?
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.OnClick(); }" />

If I got you right, you can manipulate the behavior of all update panels on page via property called a updateMode (Conditional, Always). Changing one updatepanel will cause refreshing of all, if all have mode set to Always.

Related

Hide or insert tbody and tr tag in hidden gridview?

I'm trying to validate a page on our ASP.Net site that the developers used a gridview on. It seems that initially they are using a "placeholder" gridview that is getting hidden or visible based on some buttons being clicked to show data. Before these button clicks however, I'm seeing an empty table and the validation tool I'm using is complaining about no tbody or tr tags. Is there a way to completely hide the table tag or alternately to insert a tbody/tr within the hidden gridview?
Here is the gridview tag in the aspx.vb file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" summery="This table displays system notification items."
AllowPaging="True" PagerSettings-Position="Top" PagerStyle-HorizontalAlign ="Right" PageSize ="15" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="image1" runat="server" ImageUrl="~/cmsicons/flag_red.gif" AlternateText="Overdue" Visible='<%# Eval("IsVisible")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataFormatString="{0:MM/dd/yyyy}" DataField="showdate" HeaderText="Due Date"
SortExpression="showdate" />
<asp:BoundField DataFormatString="{0:MM/dd/yyyy}" DataField="ModifiedDate" HeaderText="ModifiedDate"
SortExpression="ModifiedDate" />
<asp:TemplateField HeaderText="Data ID" SortExpression="DataRecordID">
<ItemTemplate>
<asp:HyperLink text='<%# Eval("DataRecordID") %>' runat="server" NavigateUrl='<%# Eval("DataRecordID", "CMSManageAllDataRecord.aspx?dataid={0}") %>' ></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RecordName" HeaderText="Title"
SortExpression="RecordName" />
<asp:BoundField DataField="subcdrl" HeaderText="CDRL Number"
SortExpression="subcdrl" />
<asp:BoundField DataField="subcdrl" HeaderText="Sub Cdrl Count"
SortExpression="subcdrl" Visible ="false" />
<asp:BoundField DataField="StatusName" HeaderText="Status"
SortExpression="StatusName" />
</Columns>
<EmptyDataTemplate>
<div>No Data found</div>
</EmptyDataTemplate>
<FooterStyle CssClass="GridViewFooterStyle" />
<RowStyle CssClass="GridViewRowStyle" />
<SelectedRowStyle CssClass="GridViewSelectedRowStyle" />
<AlternatingRowStyle CssClass ="GridViewAlternatingRowStyle" />
<PagerStyle CssClass="GridViewPagerStyle" HorizontalAlign="Right" />
<HeaderStyle CssClass="GridViewHeaderStyle" />
</asp:GridView>
And here is the output I see when I view source:
<div class="AspNet-GridView" id="ctl00_ContentPlaceHolder1_GridView1">
<table cellpadding="0" cellspacing="0" summary="">
</table>
</div>
You can definitely hide it with Javascript, if that's an option, one way would be
<script>
function hideGV(){
document.getElementById('<%=GridView1.ClientID%>').style.display='none';
}
</script>
If rather want to insert the tbody/tr elements and using jQuery is an option for you, here's an example.
jQuery option to insert tbody/tr
<script>
​$(function(){
$('#<%=GridView1.ClientID%>').append('<tbody><tr><td></td></tr></tbody>');
});​
</script>

Could not Update Text box control values

I am really frustrated to find a solution for my scenario. I have two gird when First grid is used show the shop information and the second grid is used to edit the offers related to the shop information. When the users edit the second grid i will just update the text box values related to the grid selection row. in my code behind file i can see the data fetching from the grid and assigning into the text boxes but when the function call (imgEdit_click) finished the page does not show the values. Editing functionality can be done in many ways but my scenario is what i explained earlier . I have the checked page there is no Postback action has been called after the method I could not find the solution can anyone help me to figure it out.
Following are my source and code behind codes.
My design Source :
<div class="field">
<asp:TextBox ID="txtareaOfferDesc" runat="server" TextMode="MultiLine" ></asp:TextBox>
</div>
<div class="field">
<asp:TextBox ID="txtTimeStarts" runat="server" CssClass="textfield"></asp:TextBox>
<cc1:CalendarExtender
ID="CalendarExtender2"
runat="server"
TargetControlID="txtTimeStarts"
CssClass="CalendarCSS">
</cc1:CalendarExtender>
<div class="datefld">
<label class="name">Offer end date/time (optional)</label>
<div class="field">
<asp:TextBox ID="txtTimeEnd" runat="server" CssClass="textfield"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender4" runat="server" TargetControlID="txtTimeEnd"
CssClass="CalendarCSS">
</cc1:CalendarExtender> `
<asp:GridView ID="gvShopDeal" runat="server" AutoGenerateColumns="false"
CssClass="tblexistoffer" DataKeyNames="ShopID" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:TemplateField>
<HeaderTemplate >
<asp:CheckBox ID="chkHeader" runat="server" />
<asp:Label ID="lblSelectAll" Text="Select All" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ShopID" HeaderStyle-Width="10%" HeaderText="Shop ID" />
<asp:BoundField DataField="ShopName" HeaderStyle-Width="40%" HeaderText="Shop Name" />
<asp:BoundField DataField="Street" HeaderStyle-Width="40%" HeaderText="Street" />
<asp:BoundField DataField="City" HeaderText ="City" />
</Columns>
</asp:GridView>
<asp:Button ID="btnCreateDeal" runat="server" Text="Create Offer"
CssClass="grnbtn" OnClientClick="return CheckDealValidation(this)" onclick="btnCreateDeal_Click"></asp:Button>
<asp:Button ID="btnDefCancel" runat="server" Text="Cancel" CssClass="greybtn"></asp:Button>
<asp:UpdatePanel ID="UpdateExistingOffer" runat="server">
<ContentTemplate>
<asp:GridView ID="gvExistingOffers" runat="server" CssClass="tblexistoffer"
AutoGenerateColumns="false" DataKeyNames="OfferID" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:BoundField DataField="OfferID" HeaderText="OfferID" />
<asp:BoundField DataField="Description" HeaderText="OfferName" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:BoundField DataField="OfferType" HeaderText="OfferType" />
<asp:BoundField DataField="StartDate" HeaderText="StartDate">
<ItemStyle CssClass="Hide" />
<HeaderStyle CssClass="Hide" />
</asp:BoundField>
<asp:BoundField DataField="EndDate" HeaderText="EndDate" >
<ItemStyle CssClass="Hide" />
<HeaderStyle CssClass="Hide" />
</asp:BoundField>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" ImageUrl="~/Merchant/images/edit.jpg" runat="server" Width="25" Height="25" onclick="imgbtnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind File :
protected void imgbtnEdit_Click(object sender, ImageClickEventArgs e)
{
ImageButton btndetails = sender as ImageButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
fferIDForShop = Convert.ToInt32(gvExistingOffers.DataKeys[gvrow.RowIndex].Value);
ShopList objShopID = ShopService.GetShopID(OfferIDForShop);
(txtareaOfferDesc.Text) = gvrow.Cells[1].Text.Trim();
txtTimeStarts.Text = gvrow.Cells[4].Text;
txtTimeEnd.Text = gvrow.Cells[5].Text;
}
Thanks
Vijay
Issue is because textboxes are out of Update Panel, So just put everything in update panel it will start functioning or just comment out update panel and then try the same thing.

DomEvent. AddHandler

I am facing little issue in my web application in asp.net.
i am receiving the below error :
Error: Sys.InvalidOperationException: Handler was not added through the Sys.UI.DomEvent.addHandler method.
I have used Updatepanel and this error occurs when i try to do some 2-3 actions very quickly.
and when next time i try to do take some action my web application just hungs up.
Please suggest.
Thanks
In my case this was caused by having the 'Close' control within an Update Panel in the Modal Popup. I fixed it by creating a 'dummy' button outside of the Update Panel, and setting it as the 'CancelControlID' in the MPE attributes:
<asp:Button ID="btnDummyCloseWindow" runat="server" Style="visibility: hidden"/>
<ajaxToolkit:ModalPopupExtender ID="mpeWindow" runat="server" PopupControlID="pnlWindow"
TargetControlID="btnDummyOtherButton" BackgroundCssClass="modalBackground"
DropShadow="false" CancelControlID="btnDummyCloseWindow" />
You'll need to make sure the close button that is present within your Update Panel has actions assigned to it to close the window (e.g. mpeWindow.hide()).
It's also worth noting that I was also making use of the TargetControlID 'fix' too, where a dummy button is referenced, so ignore the TargetControlID attribute there.
I've solved the problem setting ScriptMode property of ScriptManager to Release instead of Debug
By default ScriptManager is set to Debug mode.
I had the same problem and solved by placing the ModalPopupExtender or the user control that uses ModalPopupExtender inside an update panel.
Which ever way you want to look at it, the problem is inherit in what I believe is a bug in AJAX.
The only way I was able to resolve this was to control your Sorting or Paging on the server side where you control or more specifically refresh the UpdatePanel along with making sure the ModalPopup has been kept visible!
The reason for the error is really because once you do a sort of page change on a GridView that's inside an UpdatePanel, the controls have been "lost" to the UpdatePanel.
A better explanation is here.
Here is a column from my GridView...
<asp:GridView ID="gvTETstudents" runat="server" AutoGenerateColumns="False" AllowSorting="True" CellPadding="4" ForeColor="#333333" Font-Size="Small" Width="100%"
DataSourceID="sdsTETstudents"
OnRowCreated="gvTETstudents_RowCreated"
OnRowDataBound="gvTETstudents_RowDataBound"
OnDataBound="gvTETstudents_DataBound">
<Columns>
..
..
<ItemTemplate>
<asp:UpdatePanel ID="upWEF1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnWEFCLOSE" />
</Triggers>
<ContentTemplate>
...
...
<asp:Panel ID="pnlWEF2" runat="server" style="display:none;">
<table><tr><td>
<asp:Button ID="btnWEFshow" runat="server"
Text="ALL"
Font-Size="Small" Font-Names="Arial"
ToolTip="Click here to see all of this student's work experience feedback on file" />
<ajaxToolkit:ModalPopupExtender ID="mpeWEF" runat="server"
BackgroundCssClass="modalBackground"
OkControlID="btnWEFCLOSE"
PopupControlID="upWEF2"
TargetControlID="btnWEFshow">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upWEF2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlWEF3" runat="server" CssClass="pnlEndorsed">
<div id="Hdr" style="text-align: center">
<asp:Label ID="lblWEFHdr" runat="server">** CONTACT LOG **</asp:Label>
</div>
<div id="Bdy">
<table style="width:100%"><tr><td>
<asp:GridView ID="gvWEFContactLog" runat="server"
Font-Size="X-Small" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="true" PageSize="8" AllowSorting="True" AutoGenerateColumns="False" Width="100%"
DataKeyNames="StudentContactLogID,Private,ApprenticeContactLogID"
DataSourceID="sdsWEF"
OnRowDataBound="gvWEFContactLog_RowDataBound"
OnPageIndexChanging="gvWEFContactLog_PageIndexChanging"
OnSorted="gvWEFContactLog_Sorted">
<Columns>
<asp:TemplateField HeaderText="First Entered" SortExpression="FirstEntered">
<ItemTemplate>
<asp:HiddenField ID="hfWEFStudCLid" runat="server" Value='<%# Eval("StudentContactLogID") %>' />
<asp:HiddenField ID="hfWEFAppCLid" runat="server" Value='<%# Eval("ApprenticeContactLogID") %>' />
<asp:HiddenField ID="hfPrivate" runat="server" Value='<%# Eval("Private") %>' />
<asp:HiddenField ID="hfNotes" runat="server" Value='<%# Eval("ContactNotes") %>' />
<asp:LinkButton ID="lnkWEFCLOG" runat="server"
Text='<%# Eval("FirstEntered","{0:d MMM yyyy HH:mm}") %>'></asp:LinkButton>
<a id="lnkDummy" runat="server" visible=false></a>
<ajaxToolkit:ModalPopupExtender ID="mpeWEFCLOG" runat="server"
OkControlID="btnWEFCLOSEview"
PopupControlID="upWEFCLOG"
TargetControlID="lnkWEFCLOG">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upWEFCLOG" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="pnlWEFCLOG" runat="server" class="pnlCLOG">
<asp:TextBox ID="txtWEFCLOG" runat="server"
Wrap="true"
TextMode="MultiLine"
Rows="10"
ReadOnly="true"
Width="98%">
</asp:TextBox>
<br />
<asp:Button ID="btnWEFCLOSEview" runat="server" Text="OK" Width="100%" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
<asp:BoundField Visible="False" DataField="StudentContactLogID" HeaderText="LogID"
InsertVisible="False" ReadOnly="True" SortExpression="StudentContactLogID">
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="StaffName" HeaderText="Staff" ReadOnly="True" SortExpression="StaffName" />
<asp:TemplateField HeaderText="Contact Date Time" SortExpression="ContactDateTime">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ContactDateTime","{0:d MMM yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Follow-Up Date" SortExpression="FollowUpDate">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("FollowUpDate","{0:d MMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Private" HeaderText="Private" SortExpression="Private" />
</Columns>
<EmptyDataTemplate>
No Current Entries
</EmptyDataTemplate>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="sdsWEF" runat="server" ConnectionString="<%$ ConnectionStrings:ATCNTV1ConnectionString %>"
SelectCommand="spTETStudentContactLogView" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="StudentID" Type="string" />
<asp:Parameter Name="WEF" Type="string" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</td></tr>
<tr style="text-align: center">
<td style="text-align: left">
<asp:Button ID="btnWEFCLOSE" runat="server"
Text="CLOSE"
CausesValidation="false" Font-Bold="True" Width="61px" />
</td>
</tr>
</table>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</td></tr></table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
The major point of the code above is that I have a very deep GridView inside an UpdatePanel that's inside a ModalPopUp.
Now look at what I have inside that GridView:
OnPageIndexChanging
and
OnSorted
Inside the GridView, there is another ModalPopup and TextBox. Ignore that. That's only so the user can see the comments from the student's contact log as another popup window.
So if we now go to the code behind for the above two events:
protected void gvWEFContactLog_Sorted(object sender, EventArgs e)
{
GridView gvWEFCL = (GridView)sender;
GridViewRow gvRow = (GridViewRow)gvWEFCL.NamingContainer;
UpdatePanel upWEF1 = (UpdatePanel)gvRow.FindControl("upWEF1");
if (upWEF1 != null) upWEF1.Update();
AjaxControlToolkit.ModalPopupExtender mpeWEF = (AjaxControlToolkit.ModalPopupExtender)gvRow.FindControl("mpeWEF");
if (mpeWEF != null) mpeWEF.Show();
}
protected void gvWEFContactLog_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gvWEFCL = (GridView)sender;
GridViewRow gvRow = (GridViewRow)gvWEFCL.NamingContainer;
UpdatePanel upWEF1 = (UpdatePanel)gvRow.FindControl("upWEF1");
if (upWEF1 != null) upWEF1.Update();
AjaxControlToolkit.ModalPopupExtender mpeWEF = (AjaxControlToolkit.ModalPopupExtender)gvRow.FindControl("mpeWEF");
if (mpeWEF != null) mpeWEF.Show();
}
Notice that I am not actually controlling the sorting or the paging itself. I am only forcing the GridView to call upon the main UpdatePanel (upWEF1) to refresh itself via an Update() call. The next step is to grab the ModalPopup I want to keep visible and re-Show() it!
And that's all there is to it!
I am sure there is a cleaner solution using JavaScript itself, but for me this avoids that dread meaningless error and I have a clean set of popups and update panels that can handle both hotlinks, sorting and paging as I want the GridView to perform!

PopUpExtender on ImageButton inside GridView problem

I have GridView on my asp.net page, one column in that grid is ImageButton (TemplateField with ID="imbReserve"). On click on that button I want to show PopUp, but when I put TargetControlId="imbReserve" I get error message " A control with ID 'imbReserve' could not be found". How to achieve this, on click on button inside Grid show PopUp ?
Have a look at these 2 articles, that just helped me out with this problem
Article 1: A More Traditional approach
The Following is paraphrased from the above article
The Page Code:
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
Width="95%">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="customerid" HeaderText="ID" />
<asp:BoundField DataField="companyname" HeaderText="Company" />
<asp:BoundField DataField="contactname" HeaderText="Name" />
<asp:BoundField DataField="contacttitle" HeaderText="Title" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="pnlPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
[Your Content Here]
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width:95%">
<asp:Button
ID="btnSave" runat="server" Text="Save" />
<asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
</div>
</asp:Panel>
Note that the GridView is wrapped in an update panel also that the Target Control ID for the Modal Extender is the same as the Pop Up Control ID. This is because the ModalPopUp Extender needs a target control ID and I think this solution is a better plan than using a hidden button.
Now For the Code Behind:
protected void BtnViewDetails_Click(object sender, EventArgs e)
{
// Do Anything you need to the contents of the update panel
// update the contents in the detail panel
this.updPnlCustomerDetail.Update();
// show the modal popup
this.mdlPopup.Show();
}
Article 2:Uses Clientside Javascript
The Following is paraphrased from the above article
The client side Javascript
<script type="text/javascript">
// keeps track of the delete button for the row
// that is going to be removed
var _source;
// keep track of the popup div
var _popup;
function showConfirm(source){
this._source = source;
this._popup = $find('mdlPopup');
// find the confirm ModalPopup and show it
this._popup.show();
}
function okClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// use the cached button as the postback source
__doPostBack(this._source.name, '');
}
function cancelClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// clear the event source
this._source = null;
this._popup = null;
}
Page Code:
<asp:GridView ID="gvToDoList" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Item" HeaderText="Description" />
<asp:BoundField DataField="IsCompleted" HeaderText="Complete?" />
<asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px" >
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server"
OnClientClick="showConfirm(this); return false;"
OnClick="BtnDelete_Click" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<ajaxToolKit:ModalPopupExtender BehaviorID="mdlPopup" runat="server"
TargetControlID="div" PopupControlID="div"
OkControlID="btnOk" OnOkScript="okClick();"
CancelControlID="btnNo" OnCancelScript="cancelClick();"
BackgroundCssClass="modalBackground" />
<div id="div" runat="server" align="center" class="confirm" style="display:none">
<img align="absmiddle" src="Img/warning.jpg" />Are you sure you want to delete this item?
<asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
<asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
</div>
Again note that the Target Control ID for the Modal Pop Up Extender is the same as the Pop Up Control ID. Also note the OnClientClick attribute on the button in the template field, make sure your include "return false;".
All that is needed in the code behind it the onClick (or onCommand) event handler to do what you need to do.
I've tried both of these approaches successfully.
Hope one of these two works for you.
The problem is related to the fact that the real ID is getting changed when the page get rendered to the client.
Open your page source in the browser and look at the ID that is generated from asp.net. Then use that ID inside the TargetControlID property
This kind of problem is present with all the templated controls in ASP.NET
A cleaner way will be to bind the TargetControlID property of the ModalPopupExtendr on Page Load where you can use the ClientID property dinamically generated
modalPopupExtender.TargetControlID = myTemplateControl.ClientID;

Confirm delete before deleting dataview's row

I have a GridView which supports deleting. I'd like to add a pop up window with a question like 'Are you sure you want to delete this row?'.
My code:
<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False"
ShowFooter="True" DataKeyNames="ID"
DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
<SelectedRowStyle BackColor="Lime" />
<Columns>
<asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", #"\'"));
}
}
This renders as:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
If I click OK on confirmation window, postback occurs, but nothing happens. If I comment out RowDataBound code, than delete works OK. Code whithout confirmation pop up:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
What am I doing wrong?
I believe this is an example of what you are trying to do. It's cleaner and you don't have to go nutz with the code behind.
In your code you must change ButtonType="Image" to ButtonType="Link" - then onclick="..." will be rendered without javascript:___doPostBack(...) part. And in the GridPaymentMethod_RowDataBound event set something like deleteButton.Text = "<img src=\"path_to_image\" ... />" (use html entities instead of <>).
Or you can use ImageButton with ComamndName="delete" and ConfirmButtonExtender from ASP.NET AjaxToolkit suite.
deleteButton.OnClientClick = string.Format("((!confirm('Are you sure you want to delete payment method {0}?'))?return false);", row.Name.Replace("'", #"\'"));

Resources