Search code examples
c#asp.netmessagebox

How to display Windows.Form.MessageBox in ASP.NET web application?


I want to display my validation error messages in the MessageBox. I have Four TextBoxes and One Button control. When I click the Button Control, the TextBoxes without the text to be shown in the MessageBox. I have almost done this, but the problem is When I click the Button, the MessageBox is opened as a minimized window. So it is difficult for the end user to realize. I want to display the MessageBox to the user when button clicks.

Here is my code, In the Button Click Event

ErrorMsg="";

if (TextBox1.Text == "")
{
    ErrorMsg += "Name is required!";
    ErrorMsg += "\n";
}
if (TextBox2.Text == "")
{
    ErrorMsg += "Address is required!";
    ErrorMsg += "\n";
}
if (TextBox3.Text == "")
{
    ErrorMsg += "Phone No. is required!";
    ErrorMsg += "\n";
}
if (TextBox4.Text == "")
{
    ErrorMsg += "City is required!";
    ErrorMsg += "\n";
}
if (ErrorMsg.Length == 0)
{
     //Some Code
}
else
{
    MessageBox.Show(ErrorMsg, "Existing Address", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Thanks in advance...


Solution

  • You cannot use the Windows MessageBox in an ASP.NET application. It just doesn't make sense. An ASP.NET spits HTML/javascript/CSS so that's what you should be using to inform the user that something went wrong. So for example in an ASP.NET application you could use the RegisterStartupScript method to inject javascript into the page which will execute when the page is loaded and use the alert function:

    ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('oops');", true);
    

    Other more conventional techniques to perform validation in an ASP.NET application involve using the validation controls.