Confirm Message Box with OK or Cancel option in C#

Hi  All,

I have a function call which  results in two conditions(True and False).When the condition is false,I wanted the code to display a message box with the two options (OK and Cancel) and when the user clicks the OK button It should direct to another page.

Please anyone help me with the code ( in C# ) to display a confirm message box with this two options.Its urgent.

Thanks for your help.



2/17/2009 8:46:51 AM 93655 articles. 3 followers. Follow

6 Replies

Similar Articles

[PageSpeed] 30

private void button3_Click(object sender, System.EventArgs e) 
   if (MessageBox.Show("Really delete?","Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
       // a 'DialogResult.Yes' value was returned from the MessageBox
       // proceed with your deletion
Avantha Siriwardana
Beware of bugs in the above code; I have only proved it correct, not tried it.
(Donald Knuth)

2/17/2009 9:12:20 AM


Hi  All,

I have a function call which  results in two conditions(True and False).When the condition is false,I wanted the code to display a message box with the two options (OK and Cancel) and when the user clicks the OK button It should direct to another page.

Please anyone help me with the code ( in C# ) to display a confirm message box with this two options.Its urgent.

Thanks for your help.



Please refer to the following code:

    protected void Button1_Click(object sender, EventArgs e)
        ClientScriptManager CSM = Page.ClientScript;
        if (!ReturnValue())
            string strconfirm = "<script>if(!window.confirm('Are you sure?')){window.location.href='Default.aspx'}</script>";
            CSM.RegisterClientScriptBlock(this.GetType(), "Confirm", strconfirm, false);
    bool ReturnValue()
        return false;

Gary yang - MSFT
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
2/20/2009 2:50:46 AM

If you can use modl popup, your app will look neat.

Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
2/20/2009 3:08:53 AM

Hi you can use this script for getting confirmation from the user

function ConfirmSave()
        var Ok = confirm('Are you sure want to save the changes?');
            return true;
            return false;
---------------------------------------//For redirection to the URL

function ConfirmCancel(URL)
        var Ok = confirm('Are you sure want to Cancel the changes?');
        if(Ok == true)
            //return false;

In server side you can add this line for adding attributes of onclick()

btnSave.Attributes["onclick"] = "javascript:return ConfirmSave();";           

btnCancel.Attributes["onclick"] = "javascript:ConfirmCancel('InspectionNew.aspx');";


Thanks & regards

Dhinesh paramasivam


thanks & Regards
Dhinesh paramasivam
2/20/2009 5:08:35 AM

You can do like this..

        if (true)
            //Your code
            Page.ClientScript.RegisterStartupScript(this.GetType(), "open", "show();", true);


    <script type="text/javascript">
        function show()
            if(confirm('r u sure?'))


Ram Reddy Mekha, +91-994-840-4315

Please Mark as Answer if the post helps you.
2/20/2009 5:20:56 AM


Take a hidden field, label and button and write the javascript function between the head tags as shown below


<asp:HiddenField ID="hdnbox" runat="server" />

<br />

<asp:Label ID="lblResult" runat="server"></asp:Label><br />

<asp:Button ID="Button1" runat="server" Text="Button" /></div>

<SCRIPT type="text/javascript" language="javascript">function getMessage()


var ans; ans=window.confirm('Is it your confirmation.....?'); //alert (ans); if (ans==true)











And in the code behind write this code

Page load event

Button1.Attributes.Add("onclick", "getMessage()")

button click event

If Request.Form("hdnbox") = "Yes" Then

lblResult.Text = "You have clicked Ok" ' Write the logic when Ok is clicked i.e., redirect to pag1.aspx lets say


lblResult.Text = "You have clicked Cancel" ' Write the logic when Cancel is clicked i.e., redirect to pag2.aspx lets say or do nothing

End If

Hope this will help! 



Mark as answer if this post helpfull to you.

Don't be afraid to be wrong; otherwise you'll never be right.
2/20/2009 5:25:28 AM

Similar Artilces:

Problem dealing with the confirm message box in
Hi..i am actually trying to do something like this.When a user select a particular option from a dropdown list and click a 'Go' button, a confirm message box will be displayed if the user has selected that particular option.Other options selected will not display that confirm box when the 'Go' button is clicked.Once the user press the ok button on the confirm box,it will proceed to perform other tasks.How do i do that?..I try using the following code but it doesnt really work..the confirm box will always popup everytime the 'Go' button is clicked except for the first time u clicked on it. ...

how to call a c# function if user click on ok button of java script confirm box in .net
hi, i have one problem that is i'm adding the new user to database, if that user is already exist in the database one pop up should display with message like 'user already exists are u sure you want to update the role of the user' with 'yes' and 'no ' buttons on pop up, if user click on 'yes' button then it should call edituser() method of other wise it should reset the selected controls. how to do this using extenal .js file with javascript confirm box   Hi When user click on "Yes" set a hidden field value to be "true" or "1", if user clicks on "No/Cancel" set the hidden field to be "false" or "0". Based on the hidden field value call C# function in C#.  Shekar.Y(GGKTech)http://ggktech.comDont forget to click “Mark as Answer” on the post that helped you. can u please provide me one example how to do that one This article show how to call C# function from javascript    Vikram www.vikramlakhotia.comPlease mark the answer if it helped you i'm not able to do can u please provide me how to declare hidden filed values and how to set those to confirm of javascript. i did like this:void getSelectedUserDetails()    {        newConnection.Open();     ...

Load Text box of one web form with selected list item of list box of another web form
one help please Problem is i have two web forms  1.  ForiegnkeyTest.aspx  2. foroginkeytable.aspx   step 1 1 ForiegnkeyTest.aspx one web form <head runat="server"><script language="javascript" type="text/javascript">   function popWin()   {         var confirmWin = null;      confirmWin ='foroginkeytable.aspx','anycontent',   'width=455,height=435,status');   }  </script>     <        &nbsp;<asp:TextBox ID="txtaeropuerto" runat="server" CssClass="txtBox" MaxLength="3" Width="85px"></asp:TextBox></div>        <br />        <br />        <input type="button" onClick="popWin()" value="Open Window">   step2 . foroginkeytable.aspx ( tiena una listbox cargando sobre base de datos <div>        <asp:DropDownList ID="txtciudad" runat="server" CssClass="dropdown" DataSourceID="SqlDataSourceCIUDAD"            DataTextField="CIUDAD" Da...

How To Convert web template to Forms Template
I need  Convert web template to Forms Template   There are some free c# to vb converters out there which will allow you to upload a project and convert it to vb.   The programming models for windows forms and web projects are very different there is no way to convert a web to windows forms project.      Silverlight-helpVb TipsSpace Coast .Net User Group Hey Ajax-y, This tool really helps all programmers. I thought I would share this with you in hopes that you will fine some use for it. Thanks to KamalPatel.Net for this tool. You can see the tool here.  Hope this helps!!    Please give us feedback no matter whether you get your answer.Please "mark as answer" if it's useful for youSincerely,SpongeBert...

hei guys, i need help on my application, i'm using C#.NET as front-ed and SQL as back-end, aside from a datagrid, i want to display my data using textboxes and not a datagrid, i can do it using Visual Basic 6 but since i'm a newbee at C#.NET i don't know how to do it, specially the codes, can anyone help me with it? thank you in advance! If you are doing windows development, i would suggest using 'DataForm wizard' (Use Solution Explorer-->Rightclick project-->Add new Item-->New DataForm). It will guide you through steps. If you are doing web apps. Use quickstart to learn them. (Abishek Bellamkonda)=(:-*

Web Forms Message Box
Hello, I am converting an old VB 6.0 application into a web based app with VB.NET and ASP.NET. The problem that I am having is that the old application made extensive use of popup boxes and message boxes that would ask the user a couple questions and then pass the values back to the main form and close the popup box. I have not been able to find a good way to do this using web forms. Does anyone have any suggestions on this? Thanks Torrey You will have to use vbscript or javascript to display message boxes on the client side. You can use something like this: Button1.Attr...

OK and Cancel option (confirmation)
I want to do provide ok and cancel option with ASP.Net button. Scenario : User will click on the button "Get Price". I will call some procedures / database call and manipulate some data and will calculate price. I want to show messagebox to user say ex.  "The calculated price is: 12.34. Do you want to proceed?". with OK and Cancel option. If user press OK then proceed with further operation and cancel will not do anything.  Please suggest me the code. Thanks   <asp:Button ID="myButton" runat="server" Text="Get Price"...

OK/Cancel Message box
Hi can anyone please tell me the code to include a Confirm Javascript message box in my VB.NET project...Or can some please point me to a website where i can follow an example Many Thanks Below article has info on CLient side messagebox Thank you...

Message Boxes and Web Forms
When I go to display a MsgBox(".... in my web form I get an error. Is it possible to display simple pop up messages while working with the web forms?If you don't live for something, you'll DIE for nothing!!!!!! Hi, Message Boxes are not available in You need to write custom javascript functionality for popping up messages. Herebelow is one example:- Response.Write("<script>alert('Hello');</script>") ; Thanks.regards,Harish

C#.NET in VS.NET vs. C# in Web Matrix
Hi all, I am very new to .NET ... I realized C#.NET is only available from Visual Studio.NET ... however, I realized Web Matrix also allowed us to choose C# as language but not C#.NET ... they are not the same, right? If not, then why it's in Web Matrix which runs ASP.NET?? If I need to run C#.Net, I MUST GET VS.NET, right? Can C#.NET has the abality to create chat program? Thank you very much. C#.NET and C# are the same thing. JimMS MVP ASP.NET [VC++/MFC emeritus]Old Dog Learns New TricksPreferred programming language: cuneiform on clay tablets So ... that means I can use web matrix to create C#.NET web application? Hi, yes you can. C# and C#.NET are the same languages. Grz, Kris.Read my blog. Handy Firefox plugins for web developers.Workaround for non working Mark as answer buttons....

adding an ok/cancel confirmation box
Hi,    I am trying to add the ok/cancel confirmation box in my application. The user will search for some records, and if the number of rows returned from the search result is greater than 100, then a confirmation box will be displayed saying that “there are large number of records, do you want to continue”.   I do not know the best way to do this. Can you please help me on this?  I researched on Google, and it said to add a msgbox in the toolbox. But I can’t see that in my toolbox. I also tried adding that, but didn’t find one.  Thanks, Ashu   Ther...

message box in mobile web forms
is there a way to show a messagebox (alert, warning, error), in a mobile web form???...

How to return OK or Cancel in the confirm box
Hi , I had implemented the confirm box by using Javascript in my asp code. How can I check on the condition and perform future task? My code is as follow: confirmedMsg = "Confirmed Merging";javaScript += "\n<script language=\"JavaScript\" type=\"text/javascript\">\n"; javaScript += "<!--\n";javaScript += "confirm('" + confirmedMsg + "')"; javaScript += "// -->\n";javaScript += "</script>\n"; this.RegisterStartupScript("AlertScript", javaScript);   I w...

message box with OK and CANCEL buttons
How to dreate a Message box with OK and Cancel button. And how to verify which button is pressed How to add text boxess inside Message box.   thanks and regard sankar    I had the same problem myself. It became obvious to me that client side pop-ups, alerts etc... weren't gonna do the job.  So I used this: easy to use and does the job!!  if a plain javascript alert is what you need, then it is simply:var res = confirm("Are you sure?");res is true if user cliked OK and false if they click...

Implementing .Net Form into an web form, can this be done
I am new here, but have been searching for a while, and may not have the correct lingo to find what I am looking for.  I am tasked with implementing a .exe application that was writen vb6 then converted to .net into a new website my team is developing. The idea is to put each of the 3 different forms in this .exe application of 3 different .aspx pages. I have attempted multiple things to get this into the page and even started to just rewrite it as an web form, but even then I can't reuse any of the code since the System.Web.UI.Page doesn't inherit the same functions and object of the System.Windows.Forms.Form, I have even tried having the page Inherit System.Windows.Forms.Form, and the page shows but none of the data actually populates, it just looks like a blank form...   So the question is, how do I find out more information about implementing either the full application or at least the functionality? I am not looking for someone to do the work for me, I just need to find a good starting point since I want to learn if this is possible and how to do it. Again I may not be up on all the lingo, so even giving search terms would be helpful.   Thanks, PadawangeekPadawangeekAlways learning... What you are after cannot be done.Winforms and web forms are 2 distinct technologies and their controls cannot exist together. Most of the winforms controls have an equivalent web form control, and there are some very rich we...

Confirmation Message Box with Replace and Cancel buttons
Hi,   I would like to seek help on how to create a confirmation message with Replace and Cancel buttons.  And also, how can I check if user clicked the Replace button.    Thanks.   Hi, You can create your own Cofirmation msg dialog. u require, div tag, with 2 buttons and text to display. Make this div to display(visible) when u want and allow to user to click any of the button. if clicked 'cancel' set to 'return false;' if clicked 'replace' call respective function() with ur required code in it or set a global var. with value...

Cancel response from confirm message box is not working.
Hello, I have this ScriptManager class below for the confirm message box along with the function calls from the server side for the "Ok" response.  If the response is Ok from the confirm message box, it will goes on in the code and call one of the function from the server side "PerformSearch()" and if the response is Cancel, don't do anything and close out the confirm message box.  When I click the "Cancel" button on the confirm box, it still goes on and perform a function from the server side  just like the "Ok" respons...

Dynamic Generation of Web Forms in
I am new to c# and studio as such and am seekin help for my project. It deals with generating webforms at runtime by takin in inputs from the user. The user will input no. of webfroms to be generated and all the attributes he want in them. I have got the datamodel right for this where all the info by the user is stored in sql server database. During runtime my application should read it from that database and based upon that generated these .aspx forms which can be posted online for use. I think it would help if you explained what the application would accomplish. It sounds like yo...

Creating C# web form in application
I have an application developed in In this application I want to create a webform where the code behind will be in C# as I have some functionality in C# I want to use. How can I achieve this? macca If you're using ASP.NET 2.0 this is simple- just add a new webform, and select language as c#. If you're using 1.1 or earlier, there isn't any way.My Blog...

need to use confirm boxes in a C# web page
Hi,  I am trying to use a confirm box using Javascript in a web page for C#.  What I need to do is to set a value of flag to 1(in the c# code) based on the result of the confirm box.  This is my code int flag=0; string script2="<SCRIPT language='javascript'>"+                      "var ans =confirm('Press ok or cancel');" + "</SCRIPT>";             Page.RegisterStartupScript("confirm",script2);    ...

Show Confirm dialog box in C# web application
Hi all  I want to show a message box like confirm dailog box after comairing that customer alredy exist in database and message will say "Do you want to overwrite customer data?". if "ok" is clicked then customer data will overwrite otherwise not. I know about javascript:confirm("Are you sure to overwrite?") but this will popup when we clicked on the link button like this lnkImport.Attributes.Add("onclick", "return Overwrite();");function Overwrite() {if (confirm("Are you sure you want to overwrite customer detail?")==true) return true; elsereturn false; }   But in my case i wnat to show confirm dialoge box during the process is going on, means first i look for weather customer already exist or not and if exist the confirm message will display For this i used  public void MesssageBox() {if (System.Windows.Forms.MessageBox.Show("Customer data already exists. Do you want to overwrite it?.", "Overwrite", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Asterisk, System.Windows.Forms.MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.OK) { //System.Console.WriteLine("OK Clicked"); Exist = 3; ImportCustomerData(); } } This is working fine on local machine but not on server giving following msg: Showing a modal dialog box or form when the application is not running in UserInteractive mode i...

How To Show Messages In Single-File Web Forms Pages[C#]
Dear All, I am now working with single-file Web Forms pages instead of code-behind Web Forms pages.And using C# language like this: <%@ Page Language="C#" %> Now I finished to search a special file in the PC,and then want to show a message:"File Has Been Found,You Have The Right Version". I used this line: Message.Text = "File Has Been Found,You Have The Right Version"; But it can't work. Note: (1)The searching file application is used in: void ImageButton1_Click(object sender, ImageClickEventArgs e) {} (2)I have imported name...

Returning a error message from within a .NET web service in C#
Please advise sample code for returning a error message from within a .NET web service in C#? . Thanks. Please mark the post(s) that have helped you as "Answer" refer the below article  ThanksSkuPlease remember to click “Mark as Answer” on the post that helps you.This can be beneficial to other community members reading the thread. Hi thuhue, You can throw a SoapException in your webservice and add some information in it and catch the exception in your client . Here is my codes below, hope it is helpful to ...

Delete Message "Ok, Cancel" VB.NET
Hi I'm trying to display a message box to confirm the deletion of a record in a datagrid.Thanks You can do that in the ItemCreated event:Sub dg_ItemCreated(Sender as Object, e as DataGridItemEventArgs) handles dg.ItemCreated   If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem then      Dim btn as Button = CType(e.Item.FindControl("btnDeleteID"), Button)      btn.Attributes.Add("Onclick", "return Javascript:Confirm('Are you sure?')")   End IfEnd SubSonu Kapoor [MV...

Web resources about - Confirm Message Box with OK or Cancel option in C# -

Facebook Confirms Streamlined Post Scheduling, Announces Easier Photo Uploading For Page Admins
Facebook officially announced the improvements to the post-scheduling process that began leaking out last week, as well as an easier way for ...

4th XMRV Study Fails to Confirm Association with CFS - Facebook
The CFIDS Association of America hat eine Notiz mit dem Titel 4th XMRV Study Fails to Confirm Association with CFS geschrieben. Du kannst den ...

Slide Confirms Cuts to Ad Sales Staff, Continues to Shift Focus
Late last month, we reported that direct to consumer virtual goods sales were now accounting for at least half of Slide’s revenues, and that ...

Confirm Biosciences (@ConfirmBio) on Twitter
Log in Sign up You are on Twitter Mobile because you are using an old version of Internet Explorer. Learn more here Confirm Biosciences @ ConfirmBio ...

YouTube - Halle Berry talks The Call and confirms X-Men Days of Future Past
Veröffentlicht am 02.03.2013 Tinsel Talk: The Call Exclusive interview with Halle Berry. BlackTree TV's Jamaal Finkley talks to Halle Berry ...

BP confirms TNK stake to be sold
BP is in advanced discussions with the Russian state-controlled oil company Rosneft over the sale of the British company's stake in the troublesome ...

Brussels attacks: Union confirms airport strikes will be postponed after pressure from Federal Government ...
Community and Public Sector Union has confirmed immigration and Border Force staff will postpone airport strikes after attacks in Brussels.

Rob Ford's Treatment 'Palliative In Nature,' Office Confirms 0
The Toronto politician was diagnosed with a rare form of cancer in 2014.

Apple expands iPhone silicone/leather case options, confirms iPhone SE cases will fit 5/5s
Following Apple’s special event today, the company has updated its online store to include several new accessories including new iPhone case ...

Family confirms 2 siblings with ties to New York died in Brussels attacks
Siblings Sascha and Alexander Pinczowski, who were Dutch citizens, were in the Brussels airport at the time of the attack.

Resources last updated: 3/25/2016 4:48:29 PM