How to set messagebox icon using a string variable in vb.net - vb.net

I've been trying to make a program open a messagebox with the icon identified by a string variable, but I can't figure out how! I've tried using something like this
MessageBox.Show("Message here", _
"Message", _
MessageBoxButtons.YesNoCancel, _
MessageBoxIcon. + IconVariable)
But it gives me the error:
'MessageBoxIcon' is a type and cannot be used as an expression.

I created a Function from the link suggested by #GSerg in comments.
Private Function GetIconEnum(s As String) As MessageBoxIcon
Dim icon As MessageBoxIcon
Try
icon = DirectCast([Enum].Parse(GetType(MessageBoxIcon), s), MessageBoxIcon)
Catch ex As Exception
Return MessageBoxIcon.None
End Try
Return Icon
End Function
Private Sub OPCode()
Dim IconVariable As String = "Question"
MessageBox.Show("Message here", "Message", MessageBoxButtons.YesNoCancel, GetIconEnum(IconVariable))
End Sub

Related

Me.Close not working and a Break Mode window appears

I have a class where I will get the value of username and password of my login form and pass it to admin form.
Public Property getUsername() As String
Get
Return Login.username.Text
End Get
Set(value As String)
uname = value
End Set
End Property
Public Property getPassword() As String
Get
Return Login.password.Text
End Get
Set(value As String)
pword = value
End Set
End Property
A function getName()
Public Function getName()
con.Open()
Dim sd As New SqlDataAdapter("select * from AdminAcc where Username = '" & getUsername() & "'", con)
Dim dt As New DataTable
sd.Fill(dt)
con.Close()
getName = dt.Rows(0)(1).ToString()
End Function
I want to display the name of that user in my form so I tried this one:
Private Sub AdminM_Load(sender As Object, e As EventArgs) Handles MyBase.Load
admingreeting.Text = "Hi, " + queryclass.getName()
End Sub
It is actually working, but when I try to sign out the application stops and a break mode window appears.
Private Sub btnsignout_Click(sender As Object, e As EventArgs) Handles btnsignout.Click
If MsgBox("Are you sure you want to sign out?", vbQuestion + vbYesNo) = vbYes Then
Login.Show()
Me.Close()
End If
End Sub
I tried using the me.hide() and it worked, but when I tried to login another acc, the value in the previous getName() did not change.
I'm not sure based on what you've said whether this will solve your problem, but try changing the Shutdown Mode:
If you bring up the Properties window for the project, on the Applications Tab you can set the 'Shutdown mode'. The default is when the 'Startup Form Closes'. Change it to 'When the last form closes'.

Need to Send a outlook email from form in VB.net [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Being a newbee i can only create a form in Microsoft visual studio. But my requirement is to send a out look mail while all the options should be filled in the form created in VB.net. For eg the to address will be a dropdown list in VB.net form.
Please help with this.
This is a small class that I wrote to do the exact same thing. I looked at examples online and found some very good and bad ones and made this small class. Some of the methods are setup especially for our needs, but you should be able to mould it to your needs.
Public Class Email : Implements IDisposable
Dim _e As String
Dim _item As _MailItem
ReadOnly _oApp = New Microsoft.Office.Interop.Outlook.Application
Sub New()
Try
'Dim oApp As Microsoft.Office.Interop.Outlook._Application
'If Me(Microsoft.Office.Interop.Outlook.Application)
_item = _oApp.CreateItem(OlItemType.olMailItem)
Catch ex As COMException
MessageBox.Show("There was a problem with outlook on this machine.", "No Access to Email", MessageBoxButtons.OK, MessageBoxIcon.Warning)
[Error] = True
End Try
End Sub
Private Property [Error] As Boolean = False
Private Property HasError As Boolean = False
Public Sub AddAttachement(path As String)
'Debug.Print(Path)
_item.Attachments.Add(path)
End Sub
Public Shared Function GetAccountForEmailAddress(ByVal application As Microsoft.Office.Interop.Outlook.Application, ByVal address As String) As Account
' Loop over the Accounts collection of the current Outlook session.
Dim account As Account
For Each account In application.Session.Accounts
' When the e-mail address matches, return the account.
Debug.Print(account.SmtpAddress.ToString)
If account.SmtpAddress = address.ToString Then
Return account
End If
Next
Dim message As String = $"No Account with Address: {address.ToString} exists!" & Environment.NewLine & Environment.NewLine & "Only:" & Environment.NewLine & String.Join(Environment.NewLine, GetAllEmailAccounts(application).ToArray) & Environment.NewLine & "exist on this computer."
Throw New System.Exception(message.ToString)
End Function
Public Shared Function GetAllEmailAccounts(ByVal application As Microsoft.Office.Interop.Outlook.Application) As ArrayList
' Loop over the Accounts collection of the current Outlook session.
Try
Dim acc As New ArrayList()
Dim account As Account
For Each account In application.Session.Accounts
acc.Add(account.SmtpAddress.ToString)
Next
Return acc
Catch ex As System.Exception
MyError(ex)
Return Nothing
End Try
End Function
Public Sub Send()
Try
If HasError = False Then
_item.Send()
If ShowNotification = True Then
MessageBox.Show("Email successfully sent to: " & Environment.NewLine & _e.ToString, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
Catch ex As System.Exception
MyError(ex)
Finally
End Try
End Sub
Public Sub SentTo(emailAddress As String)
For Each add In emailAddress.Split(";")
'Debug.Print(RemoveWhitespace(add))
_item.Recipients.Add(RemoveWhitespace(add))
Next
If Not _item.Recipients.ResolveAll Then
HasError = True
Throw New System.Exception("Could send email to the following addresses: " & Environment.NewLine & emailAddress.ToString)
Else
_e = emailAddress
End If
End Sub
Public Function SetupEmail(subject As String, htmlBody As String, sendUsing As String) As Boolean
'Dim defaultFolder As MAPIFolder = _oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderDrafts)
Dim html = "<html><div style="" font-size:" & FontSize & "px;font-family:" & FontFamily & ";"">"
html = html & htmlBody
Try
'item = DirectCast(Outlook.Application.CreateItem(OlItemType.olMailItem), Outlook.MailItem)
Dim account As Account = GetAccountForEmailAddress(_oApp, sendUsing)
'item = DirectCast(oApp.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
'item.Recipients.Add(EmailAddress)
_item.Subject = "--- Digital Certificate Attached ---"
_item.SendUsingAccount = account
_item.Subject = subject.ToString
_item.SendUsingAccount = account
_item.BodyFormat = OlBodyFormat.olFormatHTML
_item.HTMLBody = String.Empty
_item.HTMLBody = html
_item.BodyFormat = OlBodyFormat.olFormatHTML
Return True
Catch exception1 As System.Exception
HasError = True
MyError(exception1)
Return False
End Try
End Function
Public Property FontFamily As String = "Tahoma"
Public Property FontSize As Integer = 12
Public ReadOnly Property HasErrrors As Boolean
Get
Return HasError
End Get
End Property
Public Property ShowNotification As Boolean
Get
Return _ShowNotification
End Get
Set(value As Boolean)
_ShowNotification = value
End Set
End Property
Private Property _ShowNotification As Boolean = True
Private _disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not _disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
If _oApp IsNot Nothing Then
'Debug.Print("oWord has value")
Marshal.ReleaseComObject(_oApp)
End If
If _item IsNot Nothing Then
'Debug.Print("oWord has value")
Marshal.ReleaseComObject(_item)
End If
End If
End If
_disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
End Sub
End Class
I use it the following way:
Using myemail As New <ClassName>.Email
myemail.SentTo(emailaddress)
myemail.AddAttachement(attachment)
If myemail.SetupEmail(EmailBody, Subject, SendingEmail) = True Then
myemail.Send()
End If
End Using

How to overload a built-in vb.net function

I want to overload the built in MsgBox() function in VB.Net.
I want to add a beep every time a MsgBox pops up, but would rather not make a new function, e.g., MsgBoxWithBeep(), and do a whole bunch of find/replace in my existing code.
I can do this just fine within a module:
Public Sub MsgBox(msg As String)
Beep()
MsgBox(msg)
End Sub
But of course this ends up being an endless recursive loop.
I can't do MyBase.MsgBox() because this is not a class.
Is there an assumed class that all built-in function use like so I can do something like VbNetBaseClass.MsgBox() or some other way to get back to the original function?.
A simple solution would be to just use MsgBox to call MessageBox.Show like this:
Public Sub MsgBox(msg As String)
Beep()
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK)
End Sub
Or better yet, use the exclamation/error icons that already make a beep:
Public Sub MsgBox(msg As String)
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub
_
Edit: good point from blackwood...you can make it into a function if you need the result:
Public Function MsgBox(msg As String, _
Optional title As String = "", _
Optional msgButtons As MessageBoxButtons = MessageBoxButtons.OK, _
Optional msgIcon As MessageBoxIcon = MessageBoxIcon.None) _
As System.Windows.Forms.DialogResult
Return MessageBox.Show(msg, title, msgButtons, msgIcon)
End Function
I don't believe that you'll be able to override or overload the MsgBox() method as it is static and a standard module (as opposed to a class) as seen here within the source :
[StandardModule]
public sealed class Interaction
{
/* Other methods omitted for brevity */
public static MsgBoxResult MsgBox(object Prompt, MsgBoxStyle Buttons = MsgBoxStyle.ApplicationModal, object Title = null);
}
Your best bet is going to be to write your own method or wrapper to handle calling it with your optional overloads, etc.

How to call a public function from another form

Frm1 contains the code for validation of textbox:
Public Function AlphabeticalOnly(ByVal Str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
If reg.IsMatch(Str) = False Then
MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
End If
Return reg.IsMatch(Str)
End Function
Because there're quite an amount of validations, I don't want to repeat all the code again in the other forms.
Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDone.Click
If AlphabeticalOnly(txtName.Text) = False Then
Exit Sub
End If
...
End Sub
I tried the code above in another form, but the error list shows that AlphabeticalOnly is not declared.
Is there anything that I need to add to my code?
First of all, don't put the function on a form. If it's common code shared by all forms, put it in its own class file.
Second, this common code shouldn't be prompting the user with a message box. This function should just perform the logic and nothing more. (This also makes the function easier to unit test.) Then allow the consuming code (in this case a form) to interact with the user. (Especially since the current implementation checks the match twice, which isn't necessary.)
Since this function doesn't rely on object state, you can make it Shared. Something like this:
Public Class CommonFunctions
Public Shared Function IsAlphabeticalOnly(ByVal Str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
Return reg.IsMatch(Str)
End Function
End Class
Then on your forms you can invoke that function:
If CommonFunctions.IsAlphabeticalOnly(txtName.Text) = False Then
MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
End If

how to create shortcut on desktop in vb.net without installer

I want to create desktop shortcut for exe file through program.
I do not want to use installer to do this.
Can a piece of code in program do this?How?
Chasler has answered that question a couple of years ago here on SO.
Add a reference to the Windows Script Host Object Model
Imports IWshRuntimeLibrary
Private Sub CreateShortCut(ByVal FileName As String, ByVal Title As String)
Try
Dim WshShell As New WshShell
' short cut files have a .lnk extension
Dim shortCut As IWshRuntimeLibrary.IWshShortcut = DirectCast(WshShell.CreateShortcut(FileName, IWshRuntimeLibrary.IWshShortcut)
' set the shortcut properties
With shortCut
.TargetPath = Application.ExecutablePath
.WindowStyle = 1I
.Description = Title
.WorkingDirectory = Application.StartupPath
' the next line gets the first Icon from the executing program
.IconLocation = Application.ExecutablePath & ", 0"
.Arguments = String.Empty
.Save() ' save the shortcut file
End With
Catch ex As System.Exception
MessageBox.Show("Could not create the shortcut" & Environment.NewLine & ex.Message, g_strAppTitleVersion, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
(Source)
This code works very well
Private Function CreateShortCut(ByVal TargetName As String, ByVal ShortCutPath As String, ByVal ShortCutName As String) As Boolean
Dim oShell As Object
Dim oLink As Object
'you don’t need to import anything in the project reference to create the Shell Object
Try
oShell = CreateObject("WScript.Shell")
oLink = oShell.CreateShortcut(ShortCutPath & "\" & ShortCutName & ".lnk")
oLink.TargetPath = TargetName
oLink.WindowStyle = 1
oLink.Save()
Catch ex As Exception
End Try
End Function
Credits