"Delete Confirmation" in gridview without a template column.

I need to add a new feature "delete confirmation" popup to a finished project. And I was wondering if it is possible to implement this without changing the structure of my gridview.
So right now If there are students registered to a class, deleting the class is not allowed and throws an exception "DELETE is cancelled due to the dependency of Course - Student" . And I would like to change it to a popup confirmation where it can be deleted after confirmed.
Gridview(a part of it) and c# snippets are below

So when it comes to delete function all i need to add is :
Delete from UserProfileClass where ClassDefId='" + DBKey + "'";
but that needs to happen after the confirmation popup.
---Gridview---
       <asp:GridView ID="GridViewClass" runat="server" 
                AllowSorting="True" DataKeyNames="ClassDefId" 
                DataSourceID="SqlDataSource3" AutoGenerateColumns="False" 
                onselectedindexchanged="GridViewClass_SelectedIndexChanged" 
                onrowcommand="GridViewClass_RowCommand" 
                onrowdeleted="GridViewClass_RowDeleted" Font-Size="X-Small" 
                style="text-align: center">
                <Columns>
                    <asp:CommandField ShowEditButton="True" ButtonType="Button" >
                        <ControlStyle Font-Size="X-Small" />
                    </asp:CommandField>
                    <asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" >
                        <ControlStyle Font-Size="X-Small" />
                    </asp:ButtonField>
                    <asp:CommandField ButtonType="Button" ShowSelectButton="True" >
                        <ControlStyle Font-Size="X-Small" />
                    </asp:CommandField>
                    <asp:TemplateField HeaderText="Course Group" SortExpression="ClassDefGroup">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEditCourseGroup" runat="server" 
                                Text='<%# Bind("ClassDefGroup") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="label23" runat="server" Text='<%# Bind("ClassDefGroup") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Course Name" SortExpression="ClassDefName">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEditCourse" runat="server" 
                                Text='<%# Bind("ClassDefName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("ClassDefName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Description" SortExpression="ClassDefDescName">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEditCourseDesc" runat="server" 
                                Text='<%# Bind("ClassDefDescName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:HyperLink ID="HyperLink4" runat="server" 
                                NavigateUrl='<%# Eval("ClassDefId", "~/FileHandler.ashx?id={0}&type=1") %>' 
                                Text='<%# Bind("ClassDefDescName") %>'></asp:HyperLink>
                        </ItemTemplate>
                    </asp:TemplateField>
 
----C#------
 
    protected void GridViewClass_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            int RowIndex = Convert.ToInt32(e.CommandArgument);
            int DBKey = Convert.ToInt32(GridViewClass.DataKeys[RowIndex].Value);
            SqlDataSource3.DeleteCommandType = SqlDataSourceCommandType.Text;
            SqlDataSource3.DeleteCommand = "Delete from AvailClass where ClassDefId='" + DBKey + "';Delete from ClassDef where ClassDefId='" + DBKey + "'";
        }
    }
 
    protected void GridViewClass_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        if (e.Exception != null)
        {
            lblCourseDelError.Text = "DELETE is cancelled due to the dependency of Course - Student ";
            e.ExceptionHandled = true;
        }
    }

Open in new window

askaspAsked:
Who is Participating?
 
channa_mConnect With a Mentor Commented:
Just wrap the code in if statement as below
if ( e.Row.RowType == DataControlRowType.DataRow ) {
             LinkButton lnkDelete = (LinkButton)e.Row.Cells[1].Controls[e.Row.Cells[1].Controls.Count - 1];
        if (lnkDelete != null) lnkDelete.OnClientClick = "return confirm('Are you sure you want to delete this record?');";
}

Open in new window

0
 
channa_mCommented:
on RowDataBound even you need to add the following code
     protected void yourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
   //confirm delete
        LinkButton lnkDelete = (LinkButton)e.Row.Cells[1].Controls[e.Row.Cells[1].Controls.Count - 1];
        if (lnkDelete != null) lnkDelete.OnClientClick = "return confirm('Are you sure you want to delete this record?');";
}

Open in new window

0
 
askaspAuthor Commented:
But that means I need to have a template column for the "Delete" command right in the gridview? and in that case a linkbutton? Let me try
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
baiju_nagoriCommented:
Hi,

It is a command button, so use this... in RowDataBound  event
dim testcomm as commandbutton =
ctype(e.Row.Cells(2).FindControl("Delete"), CommandButton)
 
testcomm.attributes.Add("onclick", "return confirm('Are you sure?');")

Open in new window

0
 
channa_mCommented:
This will work with default command button
0
 
askaspAuthor Commented:
channa_m :
This is the error i get

Specified argument was out of the range of valid values.
Parameter name: index
0
 
askaspAuthor Commented:
baiju_nagori:

It doesn't know the commandbutton at all, reference issue
"commandbutton testcomm = (CommandButton)e.Row.Cells(2).FindControl("Delete");"
0
 
williamcampbellCommented:
  <asp:gridview id="myGrid" runat="server"
      width=90% gridlines="both" cellpadding=5
      backcolor="ghostwhite"
      datasourceid="messages"
      datakeynames="messageid"
      autogeneratecolumns=false
      allowpaging
      onRowDataBound="addConfirm">   <==== see below for a sample
<script language="C#" runat="server">
   void addConfirm ( Object src, GridViewRowEventArgs e ) {
      if ( e.Row.RowType == DataControlRowType.DataRow ) {
         DataRowView rowView = ( DataRowView ) e.Row.DataItem;
         string sender = rowView [ "messagefrom" ].ToString ( ).Trim ( );
         LinkButton linkButton = ( LinkButton ) e.Row.Cells [ 0 ].Controls [ 0 ];
         linkButton.Attributes [ "onClick" ] = 
            "javascript:return confirm ( 'This procedure will delete this message from " + 
                sender + ". Confirm?' )";
      }
   }
</script>

Open in new window

0
 
askaspAuthor Commented:
williamcampbell:
Again the same error I am getting..:(
for this line >> LinkButton linkButton = ( LinkButton ) e.Row.Cells [ 0 ].Controls [ 0 ];

Specified argument was out of the range of valid values.
Parameter name: index
0
 
askaspAuthor Commented:
channa_m:
I just tried it..and this time I think the link button vs button conflicts.
This is the error i get:
Unable to cast object of type 'System.Web.UI.WebControls.DataControlButton' to type 'System.Web.UI.WebControls.LinkButton'.
But at least I didn't get an error about the index range this time.

0
 
channa_mCommented:
Oh, I did't notice you have ButtonType="Button",  Instead of LinkButton just use Button
if ( e.Row.RowType == DataControlRowType.DataRow ) {
             Button lnkDelete = (Button)e.Row.Cells[1].Controls[e.Row.Cells[1].Controls.Count - 1];
        if (lnkDelete != null) lnkDelete.OnClientClick = "return confirm('Are you sure you want to delete this record?');";
}

Open in new window

0
 
askaspAuthor Commented:
Thank you:)
Now I am getting the confirmation window however it is not initiating the delete command at all which was my initial goal. And the new code is below.
So How can I pass that to my actual delete command?
    protected void GridViewClass_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button lnkDelete = (Button)e.Row.Cells[1].Controls[e.Row.Cells[1].Controls.Count - 1];
            if (lnkDelete != null) lnkDelete.OnClientClick = "return confirm('Are you sure you want to delete this record?');";
        }
    }
 
   protected void GridViewClass_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        TextBox txtEditCourse = GridViewClass.FindControl("txtEditCourse") as TextBox;
        TextBox txtEditCourseDesc = GridViewClass.FindControl("txtEditCourseDesc") as TextBox;
        TextBox txtEditCourseSize = GridViewClass.FindControl("txtEditCourseSize") as TextBox;
        DropDownList ddlEditInstructor = GridViewClass.FindControl("ddlEditInstructor") as DropDownList;
        DropDownList ddlEditLocation = GridViewClass.FindControl("ddlEditLocation") as DropDownList;
 
        if (e.CommandName == "Delete")
        {
            int RowIndex = Convert.ToInt32(e.CommandArgument);
            int DBKey = Convert.ToInt32(GridViewClass.DataKeys[RowIndex].Value);
            SqlDataSource3.DeleteCommandType = SqlDataSourceCommandType.Text;
            SqlDataSource3.DeleteCommand = "Delete from AvailClass where ClassDefId='" + DBKey + "';Delete from ClassDef where ClassDefId='" + DBKey + "'";
        }
    }

Open in new window

0
 
channa_mCommented:
What is the error you are getting
0
 
askaspAuthor Commented:
I am not getting any error at all. The confirmation pop-up shows when I click to delete button and neither "OK" nor "Cancel" is doing anything. So its not actually returning back to the delete function I guess.
0
 
channa_mCommented:
Try changing button type to Linkbutton,
0
 
askaspAuthor Commented:
Oh wow..interesting and now it works just fine. Thank you very much and for your patience you have been very helpful.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.