Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

"Delete Confirmation" in gridview without a template column.

Posted on 2009-05-18
16
Medium Priority
?
2,394 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

 
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
 
LVL 3

Accepted Solution

by:
channa_m earned 1000 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

721 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