return confirm inside gridview does not fire - asp.net

In my code pasted below the grid has an option to delete the row on click of remove button. Before hitting server side code i want to confirmation from the user to delete the record.
But always server side code is hit rather than the confirm popup showing first.
<asp:GridView ID="grdDelegateList" runat="server" CssClass="gridviewBorder" AutoGenerateColumns="False"
CellPadding="1" Style="margin-left: 0px" BackColor="White" Font-Names="Calibri"
BorderWidth="1px" Width="100%" AllowPaging="True" GridLines="Horizontal" RowHoverBackColor="#666666"
RowHoverForeColor="White" SelectedRowStyle-BackColor="#333333" SelectedRowStyle-ForeColor="White"
PageSize="10" OnPageIndexChanging="grdDelegateList_PageIndexChanging" OnRowCommand="grdDelegateList_RowCommand"
OnRowDataBound="grdDelegateList_RowDataBound" OnRowDeleting="grdDelegateList_RowDeleting">
<Columns>
<asp:BoundField HeaderText="Employee ID" DataField="DelegateID" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Full Name" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<p>
<%#DataBinder.Eval(Container.DataItem, "Owner.FirstName")%>
<%#DataBinder.Eval(Container.DataItem, "Owner.LastName")%>
</p>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<span style="cursor: pointer">
<asp:LinkButton ID="ImgRemove" runat="server" CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
Text="Remove" OnClientClick="return confirm(Are you sure you want to remove this Delegate);">
</asp:LinkButton></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What i want to do is show a confirm box if user presses the on button server side code (ie: row command ) event should be hit, other wise on cancel it should do nothing. but its not working.

Your code for the confirm() function is not valid.
confirm() expects a string variable (see window.confirm) yet in your case you are passing in an invalid object and would receive the error
Uncaught SyntaxError: Unexpected identifier
Update your code to be;
<asp:LinkButton
ID="ImgRemove"
runat="server"
CommandName="Delete"
CommandArgument='<%# Eval("ID") %>'
Text="Remove" OnClientClick="return confirm('Are you sure you want to remove this Delegate');">

My suggestion would be to add single quotes to the OnClientClick
OnClientClick="return confirm('Are you sure you want to remove this Delegate');
you can also try the following code:
OnClientClick="if (!confirm('Are you sure you want to remove this Delegate')) return false;"

Try below snippet.
<asp:LinkButton ID="ImgRemove" runat="server" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' Text="Remove" OnClientClick="if (!confirm('Are you sure you want to remove this Delegate?'));">
OnClientClick="if (!confirm('Are you sure you want to remove this Delegate?'));
will show the alert with Yes/No options. If you click on No then nothing will happen. If you click on Yes then corresponding code will execute

Related

class icon in gridView column using VB.net

I have one GridView and I have a CSS class called class="icon-p". I want to use this class in my GridView column "Modify", except using ButtonType="Image" and ImageUrl..`
Here is my GridView code:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CssClass="table" DataKeyNames="id_s" DataSourceID="SqlDataSource1">
<Columns>
..
<asp:CommandField CancelText="cancel" DeleteText="delete" EditText="Update" HeaderText="Modify" ShowEditButton="True" ShowHeader="True" ButtonType="Image"/>
</Columns>
</asp:GridView>
Right click on your GridView in design view then go to edit columns.
Find the commandfield and click the blue hyperlink at the bottom that says "Convert to Template".
Exit back out and go to your markup and you will find that the individual controls are there and you can get at them to set your CssClass etc. The only thing that makes it an update button is the CommandName="Update" attribute.
This article here details the conversion steps that I was trying to explain:
http://peterkellner.net/2009/09/06/detailsview-gridview-aspnet-disable-new-edit-delete-buttons/
You will then be left with something like this:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" Visible='<%# GetShowEditButton() %>'
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" Visible='<%# GetShowInsertButton() %>'
CommandName="New" Text="New"></asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" Visible='<%# GetShowDeleteButton() %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
You can then set the CssClass like this for example:
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
Visible='<%# GetShowEditButton() %>' CommandName="Edit" Text="Edit"
CssClass="icon-p"></asp:LinkButton>

Conditional Delete Button in Gridview

I have a delete button in my gridview, but I want this button not to work depending on the result of an sql query.
An example
I have a gridview with "ship containers", and I want to remove one of the container from this list, but I want to display a message "to be able to delete this container, please remove it from the products", so that if a ship container is in use, I need to prevent it from being deleted.
Here is the way you can do this:
<asp:GridView ID="EntityGridView" runat="server" DataKeyNames="DocumentId" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="False" SkinID="GridViewSmall" OnRowCommand="EntityGridView_RowCommand"
OnPageIndexChanged="EntityGridView_PageIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldThreeColumns">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" ImageAlign="Top" runat="server" ImageUrl='<% #ResolveImageUrl(Eval("Extension").ToString()) %>'
ToolTip='<%# Eval("Extension").ToString() %>' CommandName="Select" CommandArgument='<%# Eval("DocumentId") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>"
SkinID="DeletePage" OnClientClick="<%# GetDeleteConfirmation(Resources.AppResource.ConfirmDocumentDelete) %>"
CommandName="CustomDelete" CommandArgument='<%# Eval("DocumentId") %>' Visible='<% #AllowDocDelete(Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Title" HeaderText="<% $resources:AppResource,Title %>" />
<asp:BoundField DataField="Author" HeaderText="<% $resources:AppResource,Author %>" />
<asp:BoundField DataField="FileName" HeaderText="<% $resources:AppResource,FileName %>" />
<asp:BoundField DataField="Created" HeaderText="<% $resources:AppResource,Created %>" />
</Columns>
<EmptyDataTemplate>
<asp:Label ID="EmptyLabel" runat="server" Text='<%# Resources.AppResource.NoContentToDisplay %>' CssClass="NoDataLabel"></asp:Label>
</EmptyDataTemplate>
</asp:GridView>
Take notice on AllowDocDelete function that disables delete button. This function should be declared inslide your page class, something like this:
public bool AllowDocDelete(object item)
{
bool result = false;
//TODO: check your condition
return result;
}
Item object represents binded entity.

How to get cell contents in ASP.NET GridView while handling OnRowEditing?

I have a GridView with a BoundField column and quite a few item templates like the following:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" OnRowCommand="gvUsers_RowCommand"
OnRowDataBound="gvUsers_RowDataBound" DataKeyNames="UserId" OnRowEditing="gvUsers_OnRowEditing"
OnRowUpdating="gvUsers_OnRowUpdating" OnRowUpdated="gvUsers_OnRowUpdated"
DataSourceID="DataSource1" Width="807px" Height="105px"
AllowPaging="True" >
<Columns>
<asp:BoundField DataField="UserName" HeaderText="User Name"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Approver">
<ItemTemplate>
<asp:CheckBox ID="cbApprover" runat="server" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Auditor">
<ItemTemplate>
<asp:CheckBox ID="cbAuditor" runat="server" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Edit" Text="Edit" />
<asp:Label ID="lblPipe1" runat="server" Text=" | " />
<asp:LinkButton ID="btnUpdate" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Update" Text="Update" />
<asp:Label ID="lblPipe" runat="server" Text=" | " />
<asp:LinkButton ID="btnDelete" runat="server"
CommandArgument='<%# Eval("UserName") %>' CommandName="Remove"
OnClientClick="return confirm('Are you sure you want to delete this user?');"
Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
While handling the Edit link button I need to use the value in the BoundField, UserName. Unfortunately during the OnRowEditing handler, all strings are empty "". This is also true in the ensuing OnRowDataBound handler for the row in question where e.Row.RowState == DataControlRowState.Edit. Is there a way to obtain this value after the user clicks on the Edit link, and commences the OnRowEditing event?
I arrived at a solution that was a bit more complicated than I was hoping for. I'll show code later but I did the following:
Created a HiddenField to hold the
value of the cell I wanted to edit in
its view state.
In the OnRowDataBound handler, I assigned the value to the
HiddenField.
The ItemTemplate, as seen above, sends the UserName as an
argument. I store this value in
the HiddenField.
The OnRowEditing is fired after the Command handler. That is where I
read the HiddenField.
If anyone has a simpler solution I would love hear about it.
Could it be that you're using late binding in TemplatedItems without EditItemTemplates?

Two Validation Groups in a single button without client click event

In a multigrid I am validating two controls like date and amount. It is validating correctly when I press the tabevent. When I press the save button it is not validating. I am using two validations groups and two validation summary. Then in save button Ialso tried onclientclick() function with javascript it is working fine but if I give the correct value in date and amount records, it is not saving. how to over come this.
Date
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox ID="txtDate" Text='<%# Bind("AD_REF_DATE") %>' runat="server" CausesValidation="true"
ValidationGroup="group" Width="80px" AutoPostBack="true" OnTextChanged="txtDate_TextChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CompareValidator ID="dateValidater" runat="server" ControlToValidate="txtDate"
Operator="DataTypeCheck" Type="Date" ValidationGroup="group" EnableClientScript="true"
ErrorMessage="Please enter a valid date (mm/dd/yyyy)." SetFocusOnError="true" Display="None">*</asp:CompareValidator>
</ItemTemplate>
</asp:TemplateField>
Amount
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" MaxLength="17" Text='<%# Bind("AD_AMOUNT") %>' CausesValidation="true"
ValidationGroup="req" runat="server" AutoPostBack="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RegularExpressionValidator ID="regVal1" runat="server" ControlToValidate="txtAmount"
ErrorMessage="Format(13int,5deci)" ValidationExpression="^[1-9]\d{0,12}(\.\d{1,2})?%?$"
ValidationGroup="req" Display="None" EnableClientScript="true" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
validations summary:
<asp:ValidationSummary ID="ValidationSummary3" runat="server" ValidationGroup="req"
HeaderText="Amount:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="group"
HeaderText="Date:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
button save:
<asp:Button ID="ButtonSave" runat="server" CssClass="button" CausesValidation="true" Text="<%$Resources:TJFAS501, ButtonSave %>"
OnClick="ButtonSave_Click" TabIndex="6" />
How to validate this in the button save also two popup box should be shown?
You might want to try firing the validate function for both groups manually via the button's OnClientClick since you have two validation groups you need to validate against. Currently your validation is not firing because you do not have any ValidationGroup assigned to your button so it is just looking for validators with no ValidationGroup defined (yours groups are: group and req).
You can call Page_ClientValidate() via javascript to fire off the validation checks manually (be sure to set CauseValidation on your button to false) and it has an optional parameter that takes the validation group.
<asp:Button ID="yourButton" runat="server" OnClick="ButtonSave_Click"
CausesValidation="false" TabIndex="6"
OnClientClick="return (Page_ClientValidate('group') && Page_ClientValidate('req'));" />
You can read more about Page_ClientValidate on MSDN.
It would be easier to just have one validation group for each action (eg. your button) but I assume you need two groups for some reason.
Try this..
<script type="text/javascript">
function Validate() {
var isValid = false;
isValid = Page_ClientValidate('Group1');
if (isValid) {
isValid = Page_ClientValidate('Group2');
}
return isValid;
}
</script>

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