Solved

"Delete Confirmation" in gridview without a template column.

Posted on 2009-05-18
16
2,364 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

910 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

24 Experts available now in Live!

Get 1:1 Help Now