Monday, August 25, 2008

Show Message Box in Asp.net

It’s not possible to show an alert message box in asp.net using server side code (like vb.net windows apps, msgbox).

But this can be achieved by generating a client side Java Script code in a server-side event.


Code

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
showMsg(”hey there”, Me)
End Sub

Public Sub showMsg(ByVal sMsg As String, ByVal frm As Web.UI.Page)

Dim sb As New System.Text.StringBuilder
Dim oFormObject As System.Web.UI.Control

sMsg = sMsg.Replace(”‘”, “\’”)
sMsg = sMsg.Replace(Chr(34), “\” & Chr(34))
sMsg = sMsg.Replace(vbCrLf, “\n”)
sMsg = “

sb = New System.Text.StringBuilder
sb.Append(sMsg)

For Each oFormObject In frm.Controls
If TypeOf oFormObject Is HtmlForm Then
Exit For
End If
Next

oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
End Sub


Explanation:

On the button click event i write a JavaScript method to the page, the JavaScript method is displaying the message your pass to the method showMsg().

Note:
Please don’t pass special characters as the message, as they will conflict with the special characters of JavaScript and message won’t come properly.

No comments: