Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"
This demo describes the different approach to display a confirmation message when deleting a row in GridView and pass the id of the item to the confirmation message. Confirmation means a user is asked first if he/she wanted to delete a record by choosing an option (OK and CANCEL).
In this demo, we use the JavaScript confirm function for displaying the confirmation message. Now let’s create our JavaScript confirm function. To do this switch to ASPX source and add the following code block within the <head> tag like:
<head runat="server">
    <title>GridView Data Manipulation</title>
    <script type="text/javascript" language="javascript">
        function ConfirmOnDelete(item)
        {
          if (confirm("Are you sure to delete: " + item + "?")==true)
            return true;
          else
            return false;
        }
    </script>
</head>
 
Since we are done setting up our JavaScript function, we can simply call that function in our codes when deleting a row in GridView. Here are the following approaches below:
 
Option A: Using the ShowDeleteButton CommandField
The ShowDeleteButton CommandField is a built-in command in GridView to preform delete. I used this option in my previous example about “GridView Edit, Insert,Update and Delete” for deleting the data . Here’s a way to attach our JavaScript confirm in our codes when using ShowDeleteButton.
Assuming that we have this GridView Column mark up:
<Columns>
    <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true" />
    <asp:BoundField DataField="CompanyName" HeaderText="Company"/>
    <asp:BoundField DataField="ContactName" HeaderText="Name"/>
    <asp:BoundField DataField="ContactTitle" HeaderText="Title" />
    <asp:BoundField DataField="Address" HeaderText="Address"/>
    <asp:BoundField DataField="Country" HeaderText="Country"/>
    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
 
At RowDataBound event, we can add an attribute to the control for calling the JavaScript confirm function when deleting. See below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
   {
     if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
     {
       string id = e.Row.Cells[0].Text; // Get the id to be deleted
       //cast the ShowDeleteButton link to linkbutton
       LinkButton lb = (LinkButton)e.Row.Cells[6].Controls[2];
       if (lb != null)
       {
         //attach the JavaScript function with the ID as the paramter
          lb.Attributes.Add("onclick", "return ConfirmOnDelete('" + id + "');");
       }      
      }
  }
}
 
As you can see from the above code blocks, we attached the JavaScript function in the LinkButton by adding an attributes to the control. But before that we need to check the RowState of the GridView first to ensure that the GridView is not on Edit Mode. If you failed to check for its RowState then you will get unexpected outcome. Second we checked for the RowType to ensure that we are on the right track for finding the control in the GridView. Please note that GridView is composed of six RowTypes namely (DataRow, EmptyDataRow, Header, Footer, Separator and Pager), so when accessing a control at RowDataBound event of GridView you must always check for its RowType.
We used the method Controls [index] because the CommandField columns doesn’t have an ID for us to use FindControl method. In addition we cannot even set an ID to a CommandField column.
As you can see, we passed the value of 6 in the cells index. This means that the ShowDeleteButton link is located at the 7th column of the GridView (see GridView mark up above), by default cells index starts at 0.
We passed the value of 2 in the Controls index in order to get reference to the ShowDeleteButton link. Based from the GridView mark up above we can see the controls sequence at the 7th columns below.
e.Row.Cells[6].Controls[0] – index 0 reference to ShowEditButton link
e.Row.Cells[6].Controls[1] – index 1 reference to a Literal control that separates between the ShowEditButton and ShowDeleteButton.
e.Row.Cells[6].Controls[2] – index 2 reference to ShowDeleteButton link
e.Row.Cells[6].Controls[3] – you will get null reference expection when passing index 3 and up J
Option B: Using TemplateField with LinkButton
Assuming that we have this GridView Column mark up below
<Columns>
 <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true" />
 <asp:BoundField DataField="CompanyName" HeaderText="Company"/>
 <asp:BoundField DataField="ContactName" HeaderText="Name"/>
 <asp:BoundField DataField="ContactTitle" HeaderText="Title" />
 <asp:BoundField DataField="Address" HeaderText="Address"/>
 <asp:BoundField DataField="Country" HeaderText="Country"/>
 <asp:TemplateField>
      <ItemTemplate>
      <asp:LinkButton ID="LinkDelete" runat="server">Delete</asp:LinkButton>
      </ItemTemplate>
 </asp:TemplateField>
</Columns>
 
The Declarative Approach:
When using TemplateField, we can directly use the OnClientClick event the ASPNET LinkButton server control and call the JavaScript confirm function at the mark up like below:
<ItemTemplate>
 <asp:LinkButton ID=" LinkDelete " runat="server" OnClick="LinkDelete _Click" OnClientClick="return ConfirmOnDelete('');">Delete</asp:LinkButton>
</ItemTemplate>
 
Note that using the above approach we cannot directly pass the value of the id to be deleted as a paramter in the confirm function that’s why we passed an empty value.
The Code Behind Approach:
The code behind approach is almost the same as what we did using the RowDataBound event for accessing the ShowDeleteButton. See below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
{
    if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
    {
      string id = e.Row.Cells[0].Text; // Get the id to be deleted
      LinkButton lb = (LinkButton)e.Row.Cells[6].FindControl("LinkDelete"); //access the LinkButton from the TemplateField using FindControl method
      if (lb != null)
      {
        lb.Attributes.Add("onclick", "return ConfirmOnDelete('" + id + "');"); //attach the JavaScript function
      }
     }
}
}
 
The only main difference from the above approach is that we are using FindControl method for referencing the control from the TemplateField based on the LinkButton’s ID.
Here’s the screen shot below for displaying a Confirmation when deleting.
 
That’s simple!
Technorati Tags: ,,,
Posted on Sunday, February 22, 2009 1:52 AM ADO.NET , ASP.NET , JavaScript , C# , GridView | Back to top


Comments on this post: Display Confirmation Message on GridView Deleting

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Miriam

http://www.craigslistguide.info
Left by Miriam on Feb 23, 2009 8:38 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hi vinz

Really this is the best blog i ever read so long...
You are doing the great job, Keep on doing this this will help lot of developers..

Your presentation is good, i felt happy after seeing your bolg
REALLY NICE BOLG

Left by praveen khade on Mar 02, 2009 5:44 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hi vinz
can u place the code for delete a record that i confirmed
from Confirmation Message on GridView Deleting
Left by adil on Mar 30, 2009 1:42 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hi, I guess one criteria is missing for RowDataBound because it is showing 'Confirm Delete' when you click on 'Cancel' Edit for Alternate rows. The reason being the row.RowState is 'Alternate | Edit' and not just DataControlRowState.Edit. Please verify.
Left by Ketrishia on Apr 05, 2009 5:40 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
hi Im new in aso.net
this post is really good and help me to understand d grid view editable mode
Left by chanchal on Jul 05, 2009 10:36 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
HI
i to new to asp.net
I know every thing about row.state by reading this post
Left by subrahmanyam on Jul 22, 2009 8:52 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
There is a error in the example. In order to get the link button to do the delete you need to add a attribute called CommandName with value 'delete'

Further the javascript function can be simplified as ahown below.

function ConfirmDelete()
{
return confirm("Are you sure to delete?");
}


<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
ID="LinkDelete"
runat="server"
CommandName="delete"
OnClientClick="return ConfirmDelete();">Delete
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>


I want to add saying that this applies using VisualStudio 2008
Left by Bart Burkhardt on Aug 28, 2009 5:24 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
great info!!!
i want to ask!
if i have a gridview just like yours but instead the delete button is not in the gridview, its outside of the gridview. and on the gridview itself, i have a checkbox in each row, to enable user to delete one or more record at the same time(by checking the the checkbox in the gridview) now my question is?

how to display the confirmation box only when one or more checkbox is checked furthermore if i press cancel on the confirmation box i dont want it to postback!!

and this one is optional, how do you pass the id value into the confirmation box? (if using the above method)
Left by LoxZ on Sep 22, 2009 3:49 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
nice work
Left by chamara on Oct 30, 2009 6:06 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hi! I am a learner and thanks for ur code.it works
Left by vishal on Nov 17, 2009 11:09 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
hi this is very use full for me... inserted fully super very nice but delete some error ...............
Left by samy on Jan 13, 2010 4:53 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Its Working...thanks
Left by Nirmal Kumar.G on Jan 27, 2010 8:02 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
When i click delete button without selecting any checkbox, java script runs and ask for confirmation. can anyone tell how to check first whether checkbox or checkboxes in grid is selected or not. if not it will ask to select a checkbox first.
Left by maverick on Apr 10, 2010 3:57 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hello there,
Superb...!!!!! explanation is too good.. :)
Please keep posting...

Happy Coding..!!! :)

Regards,
Sharath MP
Left by Sharath MP on Aug 26, 2010 7:56 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Ok... it works til the message.
But..... how do I delete the row?

Left by Carlos Barini on Aug 31, 2010 3:50 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
@Carlos,
Check this post:
http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx
Left by Vinz on Dec 06, 2010 7:00 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Hello sir!
I am a MCA student and i tried much to implement this delete confirmation code in my application. but there is only one error that i was not able to solve and the error line is:if (e.Row.RowState != DataControlRowState.Edit) . why i don't know can you help me please......
Thanks in advance....
Left by Hiral Vyas on Apr 29, 2011 8:11 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
@Hiral,

What's the actual error you are getting?
Left by Vinz on Apr 29, 2011 11:31 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
hi!
Can you please help me out with a same code but this time in VB language?
Left by ottocris on Jun 05, 2011 1:15 AM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Use online converter tool to convert it to VB.NET or vise versa: http://geekswithblogs.net/dotNETvinz/archive/2009/04/14/c-and-vb.net-code-converter.aspx
Left by Vinz on Jun 06, 2011 1:52 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
nice...tutorial....i want to know on ok button how to add the functionality of
"protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)" event...
Left by monika on Dec 23, 2011 9:31 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Dear Vinz
Nice article. I am using AjaxToolkit verison 3.5.51116.0.
With this dll, when i am referring messagebox control, then getting error like ..

Could not load file or assembly 'AjaxControlToolkit, Version=3.0.31106.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Line 95: <cc2:MessageBox ID="MessageBox1" runat="server" />



let me explain, what have to do next. do u have dll under version 3.5. I have visual studio 2008 and ajaxcontroltoolkit 3.5.

Awaiting for ur response. Thanx in advance
Left by Nadeem kazmi on Feb 22, 2012 12:26 PM

# re: Display Confirmation Message on GridView Deleting....can any one explain me what are the conditions for NO and i want the co
Requesting Gravatar...
private void deletebtn_Click(object sender, EventArgs e)
{
DialogResult dlgResult = MessageBox.Show("Are You Sure You Want To Delete ", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dlgResult == DialogResult.Yes)
{

if (dataGridView22.SelectedRows.Count == dataGridView22.Rows.Count)
{
dataGridView22.Rows.Clear();
}
foreach (DataGridViewRow row in dataGridView22.SelectedRows)
{
//dataGridView1.Rows.Remove(row);
int IntAccountID = System.Convert.ToInt32(row.Cells[0].Value.ToString());
ConnetionString con1 = new ConnetionString();
OleDbConnection objCon1 = new OleDbConnection(con1.getConStr());
string cmd3 = "delete from tblCustomer where accountno=" + IntAccountID;

objCon1.Open();
OleDbCommand objCmd = new OleDbCommand(cmd3, objCon1);
int x = objCmd.ExecuteNonQuery();
objCon1.Close();

{
this.dataGridView22.Rows.RemoveAt(this.dataGridView22.SelectedRows[0].Index);
}
DataBind();
}
}


else if (dlgResult == DialogResult.No)
{

//can any one explain me what are the conditions for NO and i want the code for no condition where data should remain as it is ...

}
Left by sayeed bagban on Feb 23, 2012 3:04 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Thanks for this sir,but i want to show the javascript messge when gridview_SelectedIndexChanged fire
Left by arun bhardwaj on Feb 26, 2012 7:42 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
if u will be girl i will be kissing u.... fantastic code works on first shot

.*
Left by Code on Aug 16, 2012 3:54 PM

# re: Display Confirmation Message on GridView Deleting
Requesting Gravatar...
Error 2 No overload for 'GridView1_SelectedIndexChanged1' matches delegate 'System.EventHandler'

This is the error i got ... pls help me....

Left by Suresh on Nov 27, 2012 5:10 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net