Wednesday, September 9, 2009

ASP.NET Confirmation LinkButton

Below is the code to a very simple and reusable Confirmation LinkButton. Basically the control emits the standard "Are you sure?" type text before actually submitting the event allowing the user to click "Ok" or "Cancel". Just create a new .CS file and copy/paste the code below into the file. This will create the new control. Here it is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CreateSoftwareUtils.Web.Controls
{
public class ConfirmLinkButton:LinkButton
{
[
Browsable(true),
PersistenceMode(PersistenceMode.Attribute),
Themeable(true)
]
public string ConfirmationText
{
get
{
string confirmationText = ViewState["ConfirmationText"].ToString();
if (String.IsNullOrEmpty(confirmationText))
confirmationText = "Are you sure?";

return confirmationText;
}
set
{
ViewState["ConfirmationText"] = value;
}
}

protected override void OnPreRender(EventArgs e)
{
this.OnClientClick = String.Format("return confirm(\"{0}\");" + this.OnClientClick,ConfirmationText);
base.OnPreRender(e);
}
}
}





You can then reference this control in your page like any other normal LinkButton. Except there is a new property called "ConfirmationText" that you can set to specify a confirmation message, or just let it default to "Are you sure?"

No comments: