I'm trying to attach a Javascript function to confirm a delete of a record in a GridView. I know this can be done more easily using an asp:LinkButton in an ItemTemplate but I am trying to attach it to a CommandField - ShowDeleteButton button.
I've tried to follow this tutorial: display-confirmation-message-on-gridview-deleting
I am new to GridView and my implementation is in VB.Net not C#. Here is the code where I try to inject the Javascript function and I cannot figure out how/why my row.cell references are wrong:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowState <> DataControlRowState.Edit Then
If e.Row.RowType = DataControlRowType.DataRow Then 'check for RowType DataRow
Dim id As String = e.Row.Cells(0).Text 'get the position to be deleted
Try
'cast the ShowDeleteButton link to linkbutton
Dim lb As LinkButton
Dim i As Integer = 4 'cell we want in the row (relative to 0 not 1)
lb = DirectCast(e.Row.Cells(i).Controls(2), LinkButton)
If lb IsNot Nothing Then 'attach the JavaScript function with the ID as the parameter
lb.Attributes.Add("onclick", "return ConfirmOnDelete('" & id & "');")
End If
Catch ex As Exception
End Try
End If
End If
Here is my GridView markup snippet (a bit more busy than all bound columns; I count 3 TemplateField items after the first and only BoundField to arrive at the 5th column hence i = 4 above):
<Columns>
<asp:BoundField DataField="PositionID" HeaderText="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="PositionTitle">
<ItemTemplate>
<%# Eval("PositionTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPositionTitle" Text='<%# Eval("PositionTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Incumbent">
<ItemTemplate>
<asp:Label ID="lblUser" runat="server" Text='<%# Eval("Incumbent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblUser" runat="server" Text='<%# Eval("Incumbent")%>' Visible = "false"></asp:Label>
<asp:DropDownList Width="100%" runat="server"
id="ddlUsers" AutoPostBack="true"
DataTextField="FullName" DataValueField="UserID"
OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Backup">
<ItemTemplate>
<%#Eval("Backup")%>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblBackup" runat="server" Text='<%# Eval("Backup")%>' Visible = "false"></asp:Label>
<asp:DropDownList Width="100%" runat="server"
id="ddlUsersBackup" AutoPostBack="true"
DataTextField="FullName" DataValueField="UserID"
OnSelectedIndexChanged="ddlUsersBackup_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
When I ignore the error, the Command buttons are indeed in the 5th column:
The error I get without the Try/Catch is:
If you haven't figured out yet, your problem is in ButtonType="Button" here:
<asp:CommandField ButtonType="Button" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
You can't cast a command button to link button. You have to define it as Link button (please refer to MSDN for details of CommandField class). This is working:
<asp:CommandField ButtonType="Link" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
Just call a javascript function on onclientclick event and ask for confirmation. If it returns true then you can call the server side code to delete.
Below is the code for explanation
<asp:LinkButton ID="lbDelete" runat="server" OnClick="lbDelete_Click" OnClientClick="return fnConfirm();"> Delete</asp:LinkButton>
And below is the javascript function:
<script type="text/javascript">
function fnConfirm() {
if (confirm("The item will be deleted. Are you sure want to continue?") == true)
return true;
else
return false;
}
You can check the detailed article with source code in the below link
http://www.dotnetpickles.com/2013/03/how-to-show-confirm-message-while.html
Thanks
I found lots of C# answers.
aspx page:
<asp:CommandField DeleteText="Delete" ShowDeleteButton="true"
ButtonType="Button" />
aspx.vb page:
Protected Sub GridView1_RowDataBound(sender As Object, _
e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If (e.Row.RowState <> DataControlRowState.Edit) Then
Dim oButton As Button
oButton = CType(e.Row.Cells(14).Controls(0), Button)
oButton.OnClientClick = _
"if (confirm(""Are you sure you wish to Delete?"") == false) return;"
End If
End If
End Sub
Related
I've been trying to refresh a GridView when two textbox set me the range then click Search, and returns me the columns in that range.
But the thing is, in first load the GridView fills up with all the columns, that works fine but when I click search button doesn't refresh at all, it just stays the same.
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView CssClass="table" AllowSorting="true" HeaderStyle-HorizontalAlign="Center" EmptyDataText="No hay pendientes." CellPadding="10" HeaderStyle-CssClass="bg-primary p-2 text-dark bg-opacity-25" runat="server" ID="gvBitacora" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="cvebitacora" HeaderText="No" ItemStyle-Font-Bold="true" ItemStyle-Width="3%" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Formulario No." ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# String.Format("{0}-{1}", Eval("cveano"), Eval("cvenumero"))%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="cveusuario" HeaderText="Usuario" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="cveestado" HeaderText="Estado" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="observacion" HeaderText="Observación" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="fechaaccion" HeaderText="Fecha" DataFormatString="{0:dd/ MM/ yyyy}" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Revisión" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="btnVer" CssClass="btn btn-primary" runat="server" CommandName="btnVer" CommandArgument="<%# Container.DataItemIndex %>">Ver <i class='far fa-eye'></i></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
And here the Button Click in VB
Private Sub btnBuscar_Click(sender As Object, e As EventArgs) Handles btnBuscar.Click
Dim user As User = CType(Session.Item("user"), User)
Dim oBLBitacora As New BLBitacora
Dim lBitacora, lBitacora2 As New List(Of Bitacora)
If user.cverol = 2 Then
If panelsStayOpen_headingOne.Checked = True Then
lBitacora = oBLBitacora.BitacorasGetDate(dateFechaInicio.Text, dateFechaFinal.Text)
gvBitacora.DataSource = lBitacora
gvBitacora.DataBind()
End If
ElseIf user.cverol = 3 Then
lBitacora = oBLBitacora.BitacorasGet(2)
gvBitacora.DataSource = lBitacora
gvBitacora.DataBind()
End If
End Sub
GridView on first load
PAGE LOAD
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim user As User = CType(Session.Item("user"), User)
Dim oBLBitacora As New BLBitacora
Dim lBitacora, lBitacora2 As New List(Of Bitacora)
If Not IsPostBack Then
If user.cverol = 2 Then
lBitacora = oBLBitacora.BitacorasGet(1)
gvBitacora.DataSource = lBitacora
gvBitacora.DataBind()
ElseIf user.cverol = 3 Then
lBitacora = oBLBitacora.BitacorasGet(2)
gvBitacora.DataSource = lBitacora
gvBitacora.DataBind()
End If
Else
If panelsStayOpen_headingOne.Checked = True Then
panelsStayOpen_headingOne.Attributes("class") = "form-check-input"
panelsStayOpen_headingOne.Attributes("aria-expanded") = "true"
panelsStayOpen_collapseOne.Attributes("class") = "accordion-collapse collapse show"
Else
panelsStayOpen_headingOne.Attributes("class") = "collapsed form-check-input"
panelsStayOpen_headingOne.Attributes("aria-expanded") = "false"
panelsStayOpen_collapseOne.Attributes("class") = "accordion-collapse collapse"
End If
End If
where is your page load event showing the initial bind? You'll also want to be sure you call Updatepanel.Update() after the search click.
I've managed to fix it ,the Panel Update needed to be in the initial Form, not only the GridView.
I'm trying to update GridView from code behind but stuck at a problem which I don't understand even after countless searches for a solution.
After editing a textbox in GridView EditItemTemplate, clicking an 'Update' button in the row would fire RowUpdating event. In the RowUpdating event handler, I use this code to get the string of the edited txtBox1:
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
I am able to get a correct value for text1 but the problem is if I wrote GridView1.DataBind() in the same even handler, the code above will cause the error "Object reference not set to an instance of an object." I could not understand why the same code will work if delete/comment out GridView.DataBind() method.
I've been stuck with this problem for many days and I will really really appreciate any help.
Here's my VB.net code to handle GridView1.RowUpdating. This will only work if I delete or comment out GridView1.DataBind() method but GridView won't be updated with new data :
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim text1 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox1"), TextBox)).Text
Dim text2 As String = (CType(GridView1.Rows(e.RowIndex).FindControl("txtBox2"), TextBox)).Text
Dim IDkey As String = GridView1.DataKeys(e.RowIndex).Values(0).ToString()
Dim sqlquery As String = "UPDATE tblPMU SET zone = '" & text1 & "', substation ='" & text2 & "' WHERE (ID ='" & IDKey & "')"
Dim sqlCmd As New SqlCommand(sqlquery, conn)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
conn.open()
Dim dt As New DataTable()
sqlDa.Fill(dt)
conn.Close()
GridView1.EditIndex = -1
UpdateGridview()
GridView1.DataBind()
Label5.Text=text1
End Sub
My .aspx code for the GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" ReadOnly="True" Visible="False" />
<asp:TemplateField HeaderText="subzone" SortExpression="zone">
<EditItemTemplate>
<asp:TextBox ID="txtBox1" runat="server" Text='<%# Bind("zone") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("zone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="substation" SortExpression="station">
<EditItemTemplate>
<asp:TextBox ID="txtBox2" runat="server" Text='<%# Bind("station") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("station") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have following gridview in aspx page:
<asp:GridView Runat="server" id="gv1" PageSize="20" Visible="False" AllowPaging="True" Width="100%"
CssClass="clsDataGrid" AutoGenerateColumns="false" DataKeyNames="intProofSLNo,txtAdminRemarks" CommandArgument='Eval(intProofSLNo,txtAdminRemarks)'
OnRowCommand="gv1_RowCommand" OnRowDataBound ="gv1_OnRowDataBound" >
<asp:BoundField DataField="intProofSLNo" ReadOnly="True" Visible="false" ItemStyle-Wrap="false" HeaderText="Sl No" ItemStyle-CssClass="clsNormalText"></asp:BoundField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnApprove" runat="server" CommandName="Approve" Text= "Approve / " />
<asp:LinkButton ID="lnkbtnReject" runat="server" CommandName="Reject" Text= "Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Admin Remarks">
<ItemTemplate>
<asp:Label ID="lblAdminRemarks" runat="server" ItemStyle-Wrap="True" Text='<%# Bind("txtAdminRemarks")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAdminRemarksEdit" runat="server" cssclass=clsCommonInput MaxLength="252" Text='<%# DataBinder.Eval(Container.DataItem, "txtAdminRemarks")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" Text="Edit" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" Width="38" runat="server" Text="Update|" CommandName="Update"CommandArgument='<%# Container.DataItemIndex %>' CausesValidation="true" ToolTip="Save"> </asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Width="40" Text="Cancel" CommandName="Cancel"
CausesValidation="false" ToolTip="Reset"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The user clicks on the 'Edit' link which makes 'Update' and 'Cancel' links visible.It then enters the remarks in the textbox and clicks 'Update'.A row command event is fired which updates the remarks in DB for the entry in that particular row. The same event calls the bind function:
Protected Sub gv1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Update" Then
//some code to update remarks//
gv1.EditIndex = -1
subBindDataGrid()
End If
The subBindDataGrid() fires the following rowbound event which hides the buttons depending on admin remarks:
Protected Sub gv1_OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblAdminRemarks As Label = DirectCast(e.Row.FindControl("lblAdminRemarks"), Label)
Dim lnkReject As LinkButton = DirectCast(e.Row.FindControl("lnkbtnReject"), LinkButton)
Dim lnkApprove As LinkButton = DirectCast(e.Row.FindControl("lnkbtnApprove"), LinkButton)
Dim lnkEdit As LinkButton = DirectCast(e.Row.FindControl("lblEdit"), LinkButton)
If DataBinder.Eval(e.Row.DataItem, "txtAdminRemarks").ToString().Trim = "Auto-Approved" Then
lnkApprove.Visible = False
lnkReject.Visible = False
lnkEdit.Visible = False
Else
lnkbtnApprove.Visible = True
lnkbtnReject.Visible = True
End If
End If
The remarks get updated in the DB. However, there is some issue in binding and instead of displaying the grid, the page is redirected to an error page. There is no exception thrown anywhere while debugging. The same events are also called in 'Edit'command. However, the functionality works fine there.Please suggest if there is anything wrong with the syntax.
I see you don't define a DataSourceID on the GridView static definition, please make sure you define a DataSource for the GridView in the subBindDataGrid procedure, otherwise it will have a null datasource in input.
Hi all I have a simpe ASP button inside a grid. But the onclick event doesn't seem to fire. Where did I go wrong?
Here's the first line of my aspx page.
<%# Page Title="Trainer Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeFile="TrainerData.aspx.vb" Inherits="TrainerData"%>
And the button inside my gridview..
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" OnClientClick="btnExecutiveGenerate_Click" />
</ItemTemplate>
</asp:TemplateField>
P.S. I tried even onclick but it doesn't work either.
EDIT: My code for server side.
Protected Sub btnExecutiveGenerate_Click(sender As Object, e As EventArgs)
Dim gvrow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim lblSchoolId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblSchoolMasterID")
Dim lblFacultyId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblFacultyMasterID")
Dim btnExecutiveGenerate As System.Web.UI.WebControls.Button = gvrow.FindControl("btnExecutiveGenerate")
PDF_Creation_Executive(Val(lblSchoolId.Text), Val(lblFacultyId.Text))
End Sub
Use Command Argumnet,
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
add code page side
Protected Sub GridView1_RowCommand(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
You need to handle the button click event of Gridview in RowCommand event
NOTE: Please see the CommandName & CommandArgument properties added to the button.
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" OnRowCommand="gvExecSummary_RowCommand" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" CommandName="GenerateExecutive" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
And and RowCommand event will be..
protected void gvExecSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GenerateExecutive")
{
// button click code goes here
}
}
change OnClientClick event to OnClick if btnExecutiveGenerate_Click is vb.net event handler
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate"
OnClick="btnExecutiveGenerate_Click"/>
OnClientClick event use to execute client-side script, if you have given OnClientClick event with OnClick event, then if OnClientClick return true only it will call OnClick event.
so make sure you are returning true or false from OnClientClick event if you using it.
note that if you are loading data in page laod, do as below
Sub Page_Load
If Not IsPostBack
LoadGridViewData()
End If
End Sub
This may help someone, but I was experiencing edit buttons not firing the event within rows (and not footer).
The cause was a gridview containing a label, which had the same ID as one elsewhere on the page.
Seemingly this did not cause problems for the footer row, which did not contain any such labels.
I hope this helps someone.
This is my Gridview code
<asp:DataGrid id="dg" runat="server" ondeletecommand="Delete_Item" >
<columns>
<asp:buttoncolumn buttontype="LinkButton" commandname="Delete" text="Remove" />
</columns>
<HeaderStyle BackColor="#95C736" ForeColor="White" Font-Bold="True" />
</asp:DataGrid>
I want to replace my buttoncolumn with an image, what must I do to my GridView?
I would use a template column for this:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/delete.png" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Replace the Button Column with a TemplateColumn with allows you to put standard asp controls inside. Then you can handle the Datagrid_ItemCommand event normally.
<asp:DataGrid ID="dgTest" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" CommandName="cmdDelete"
ImageUrl="~/images/delete.png" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
The ItemCommand handler would be something like:
Protected Sub dgTest_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgTest.ItemCommand
If (e.CommandName = "cmdDelete") Then
Response.Write("the command argument was :" & e.CommandArgument)
End If
End Sub
The only other thing you would need to do is bind some data to the image button for a command argument. I usually do something like:
Protected Sub dgTest_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgTest.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim di As FAQTable = e.Item.DataItem
DirectCast(e.Item.FindControl("ibtn"), ImageButton).CommandArgument = di.FAQID
End If
End Sub
You could also use an asp:image control with an asp:Hyperlink control to get the same results.
One thing I just did that worked awesome is to put encoded html into the text. Text="<img src='images/btn-find.png' class='ttip' alt='View Details' />" This let me know only put in the img src, but also specify a class and an alt tag.
All you need to do is use single tick marks and encode your <> with gt and lt.