Solved

"Delete Confirmation" in gridview without a template column.

Posted on 2009-05-18
16
2,360 Views
Last Modified: 2013-12-17
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

0
Comment
Question by:askasp
16 Comments
 
LVL 3

Expert Comment

by:channa_m
ID: 24416442
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
 

Author Comment

by:askasp
ID: 24416458
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
 
LVL 4

Expert Comment

by:baiju_nagori
ID: 24416461
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
 
LVL 3

Expert Comment

by:channa_m
ID: 24416507
This will work with default command button
0
 

Author Comment

by:askasp
ID: 24416554
channa_m :
This is the error i get

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

Author Comment

by:askasp
ID: 24416563
baiju_nagori:

It doesn't know the commandbutton at all, reference issue
"commandbutton testcomm = (CommandButton)e.Row.Cells(2).FindControl("Delete");"
0
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24417089
  <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
 

Author Comment

by:askasp
ID: 24417601
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 3

Accepted Solution

by:
channa_m earned 250 total points
ID: 24417853
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
 

Author Comment

by:askasp
ID: 24418011
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
 
LVL 3

Expert Comment

by:channa_m
ID: 24421734
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
 

Author Comment

by:askasp
ID: 24423426
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
 
LVL 3

Expert Comment

by:channa_m
ID: 24423780
What is the error you are getting
0
 

Author Comment

by:askasp
ID: 24423876
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
 
LVL 3

Expert Comment

by:channa_m
ID: 24424245
Try changing button type to Linkbutton,
0
 

Author Comment

by:askasp
ID: 24424338
Oh wow..interesting and now it works just fine. Thank you very much and for your patience you have been very helpful.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now