I wish to display a MessageBox when a user had entered an invalid input in a textbox. How can I do this using C# as my script?

< %@ Page Language="C#" %> 
< script runat="server">  
   void AlertBtn_Click(object sender, EventArgs e) 
   { 
       string showmessage = "Test Message Box"; 
       string alertScript = "< script language=JavaScript> "; 
       alertScript += "alert('" +showmessage +"');"; 
       alertScript += "< /script" +"> "; 

       if (!IsClientScriptBlockRegistered("alert")) 
           this.RegisterClientScriptBlock("alert", alertScript); 
   } 
< /script>  
< html>  
< head>  
< /head>  
< body>  
   < form runat="server">  
       < asp:Button id="btn" onclick="AlertBtn_Click" 
 runat="server" Text="Button"> < /asp:Button>  
   < /form>  
< /body> 
< /html>

<script language="javascript" type="text/javascript">
function confirm()
{
if (confirm ==true)

else

return false;

}
</script>
then write in .aspx.cs
ButtonSave.Attributes.Add("onclick", "return confirm('Are you sure you proceed?');");

hope this code will help you out.

Thank tou
Jitesh
.Net Consulting

Thanks. But just a sort of clarification, let's say what if a user had entered an invalid age in a textbox. And then a messagebox will pop up with a message "Sorry, your age is not qualified!". How can I do this?

hi ebabes,


if you use the dropdownlist and add the number in to it, then there is no question of user making the mistake and so no need to prompt too..

Visual Basic code

Private flag As Boolean

Private Sub MyTextChangedHandler(sender As System.Object, e As System.EventArgs)
' Check the flag to prevent code re-entry.
If flag = False Then
' Set the flag to True to prevent re-entry of the code below.
flag = True
' Determine if the text of the control is a number.
If IsNumeric(textBox1.Text) = False Then
' Display a message box and clear the contents if not a number.
MessageBox.Show("The text is not a valid number. Please re-enter")
' Clear the contents of the text box to allow re-entry.
textBox1.Clear()
End If
' Reset the flag so other TextChanged events are processed correctly.
flag = False
End If
End Sub

Hope this will help you out.

Thank you
Jitesh
.Net Consulting

Thanks buddy! But what if I make use of C# as my script? This is what I need. Can you help me please!

This article has been dead for over six months. Start a new discussion instead.