Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding a confirmation script to a datagrid button

Best Practices

Adding a confirmation script to a datagrid button

by  Alcar  Posted    (Edited  )
Greetings all,

many times I have seen this question posted in different forums. I, myself had asked it time ago and eventually found a solution.

Is there a way to add a confirmation message to a delete button of my datagrid?

There sure is. The javascript is pretty easy:
javascript: return confirm('Are you sure you want to delete this record?');

The problem is adding it to a button that is created on-the-fly. The best way to access this button is by casting it after it's created and before it's pressed, and the only place where we can do this is in the ItemCreated Event:

private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
ListItemType lit = e.Item.ItemType;
if (lit == ListItemType.Item)
{
Button btnDelete = (Button) e.Item.FindControl("btnDelete");
btnDelete.Attributes.Add("OnClick", "javascript: return confirm('Are you sure you want to delete this record?');");
}
}

et voila'
now we have a delete button that will ask for a confirmation before executing it's code.

I hope this will help most of you, and I hope this Faq finds you in great health.

Happy Coding!

Daren J. Lahey
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top