Avoid Existing Items in TextBox - vb.net

Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub
I write a code for moving an item from ListBox to RichTextBox.
How to validate if a list item is already exist or not.

As vinayak, said, you can use .contains() to know if the text box contains the string or not
Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
'check if the item already exists
If RtMsgContent.Text.Contains(LBMessageContents.SelectedItem) then
'do what you want to do if the item already exists. like showing message
MsgBox("Error! This item already exists")
Else
'doesn't already exists, add to the textbox
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub

I got the solution for my question.
I used the [.contains()] function to validate the text is already exists or not.
Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
**If RtMsgContent.Text.Contains(LBMessageContents.SelectedItem) then Exit Sub**
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub

Related

Pass Information between 2 Forms - VB.Net - Winforms

I have 2 Forms in a Product Registration Project
The 1st form has 3 buttons: New | Consult | Change | - that call the 2nd Form where I have a Photo Button.
New Button:
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Consult Button:
Private Sub tsbConsult_Click(sender As Object, e As EventArgs) Handles tsbConsult.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.txtDes.Enabled = False
frm.txtDesRed.Enabled = False
frm.ShowDialog()
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
End Sub
Change Button
Private Sub tsbChange_Click(sender As Object, e As EventArgs) Handles tsbChange.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
In the 2nd Form, the Photo button will have two different behaviors:
when the user has clicked on the "New" button on Form 1, the code will open a search screen for the user to select an image in a folder on the Photos in server and show it in the picturebox1 in Form 2;
when the user has clicked on the "Consult" or "Change" button on Form 1, the code will make a comparison between the prdCod field of the Products Table and the filename of the image in the Photos folder and, when found, will show the image in the picturebox1 in Form 2.
If the "clicked button" on form 1 is "New", do the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Using open As New OpenFileDialog With {
.Title = "Select Photo",
.FileName = "",
.Filter = "Images PNG,JPEG,BMP,JPG|*.png;*.jpeg";*.bmp;*.jpg,
.Multiselect = False}
If open.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(open.FileName)
End If
End Using
End Sub
If the "clicked button" on form 1 is "Consult or Change", execute the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Dim IdProduto As String = prdCod ***field Products Table that will be used for the search in the Photos folder
If File.Exists("\\server\cmg\projects\Photos" & IdProduto) Then ***Search the image from the Photos folder on the server
PictureBox1.Image = Image.FromFile("\\server\cmg\projects\Photos" & IdProduto)
End If
End Sub
How do I check which button was clicked on the 1st form to be able to perform the correct Private Sub on the 2nd form?
It worked:
In the first form (frmConsProd), in the New Button code (tsbNew_Click), I include the parameter that will be sent to
the second form (frmCadProd):
Public Class frmConsProd
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frmCadProd("New")
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
In the second form (frmCadProd) I created a class variable (_operation) and the constructor (Public Sub New) to receive the sent parameter:
Public Class frmCadProd
Dim _operation As String
Public Sub New(operation As String)
InitializeComponente()
Select Case operation.ToLower()
Case "new"
_operation = operation
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
End Class
Thanks to Messrs. #F0r3v3r-A-N00b, #jmcilhinney e #user09938, for the help.

Backgroundworker gives multiple error messages

I have a form with three textboxes in it. In my BackgroundWorker1_DoWork handler I test if any TextBox is empty and launch a MessageBox asking the user to fill in all the TextBoxes. This is done in a Try/Catch block. My problem is two fold. If the TextBoxes aren't filled in the user gets the first MessageBox and then another MessageBox when the Catch exception is thrown...so this would be the second MessageBox the user gets. In my BackGroundWorker1_RunWorkCompleted handler I test if an Exception is thrown. It never acknowledges the error and immediately executes the Else block which will be the third message box the user receives saying "Process complete." The Process Complete should not have been shown.
How do I test if there are any TextBoxes not filled in and if they're not throw 1 MessageBox telling the user to fill in all the TextBoxes? And make my RunWorkerComplete handler acknowledge the ElseIf e.Error IsNot Nothing.
Thank you for your help.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Try
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
End If
End If
Next
runProgram()
Catch ex As Exception
MessageBox.Show("An error occured while trying to load this application. Please contact Maxine Hammett for assistance " &
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
ElseIf e.Error IsNot Nothing Then
MsgBox("Error in RunWorkerComplete" & e.Error.Message)
Else
MsgBox(" Process Complete ")
Close()
End If
End Sub
Moved the control checking to the execute button. But now I get errors about the text boxes not having a path (one of the text boxes is a path to folder).
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim launchProgram As Boolean = False
While launchProgram = False
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
launchProgram = False
Else
launchProgram = True
End If
End If
Next
End While
If launchProgram = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I suggest that you check a single text box a time and show the message if its empty:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
Return
Else
cntrl.BackColor = SystemColors.Window
End If
Next
BackgroundWorker1.RunWorkerAsync()
End Sub
Or maybe concatenate the names of the empty text boxes in the For..Each block if you really need to prompt the user this way:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim sb As New StringBuilder
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
If sb.Length > 0 Then sb.Append(", ")
sb.Append(cntrl.Name)
cntrl.BackColor = Color.Yellow
Else
cntrl.BackColor = SystemColors.Window
End If
Next
If sb.Length > 0 Then
MessageBox.Show("Please enter value in all fields on form" & sb.ToString())
Controls.OfType(Of TextBox).Where(Function(a) String.IsNullOrEmpty(a.Text)).FirstOrDefault?.Focus()
Return
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
Otherwise, run the worker.
Good luck.

Deletion of image from folder that is referenced to picture box

sorry i have to rewrite this question as i did not get any update on my same question posted previously.
Below is the code where I'm inserting some data into Ms Access database in visual studio using vb. Net.
When i insert the data i also browse the image for that item and save into the folder that is located under project directory for universal access.
There is a datagridview which displays the data which was inserted to access databas alog with the image in picture box. Whenever the the datagrid view selection is change it display the picure into picture box.
I am having a trouble when i want to delete the data along with image located in project folder as it show the error that 'file used by another process, cant be deleted'
Since i have referenced that image to my picture box, it can not be deleted directly. So here I'm looking for a solution which can display the clone of image in picture box instead of real object.
Below is my code
Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
frmTable.Show()
End Sub
End Class

setting Withblock variable or object variable in VB 2015

Public Class Form1
Private ContactsTableBindingSource As Object
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ContactsTableDataSet.Table' table. You can move, or remove it, as needed.
Me.TableTableAdapter.Fill(Me.ContactsTableDataSet.Table)
If ComboBox1.Text = Nothing Then
Try
ContactsTableBindingSource.AddNew()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If First_NameTextBox.Text = Nothing Then
First_NameTextBox.Text = "unknown"
End If
If Last_NameTextBox.Text = Nothing Then
Last_NameTextBox.Text = "unknown"
End If
If AddressTextBox.Text = Nothing Then
AddressTextBox.Text = "unknown"
End If
If Phone_NumberTextBox.Text = Nothing Then
Phone_NumberTextBox.Text = "unknown"
End If
If Email_AddressTextBox.Text = Nothing Then
Email_AddressTextBox.Text = "unknown"
End If
Try
Me.Validate()
Me.ContactsTableBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ContactsTableDataSet)
MessageBox.Show("The data has been saved", "Information", MessageBoxButtons.OK)
ContactsTableBindingSource.AddNew()
First_NameTextBox.Select()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Please suggest a correction in the code as I have being showing the error "object variable or Withblock not set"

VB.Net SelectedChangeCommitted Throwing Error

I am really annoyed here. I don't understand why this event keeps throwing a blank error. Below is my code.
Private Sub cboSections_SelectedChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cboSections.SelectionChangeCommitted
On Error GoTo EH
If TypeOf sender Is Windows.Forms.ComboBox Then
'some boolean that checks if we are skipping this event, thus it does if so
If mbSkipEvent Then Exit Sub
'checks if index that was changed to is > 0 then it toggles the bottom command buttons
If cboSections.SelectedIndex > 0 Then
ToggleCmdButtons(True)
Else
ToggleCmdButtons(False)
End If
'sets the string msPurpose
msPurpose = "Show Section"
Debug.Print("Im here")
End If
EH:
Debug.Print("Error Description: " & Err.Description)
End Sub
In my output I get "Error Description: ". Thats it. If anyone has any solution or point in the right direction that would be great.
Let's try some real error handling and see if you get anything better. While we're at it, we can simplify the code a bit:
Private Sub cboSections_SelectedChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cboSections.SelectionChangeCommitted
Dim comboBox = TryCast(sender, ComboBox)
If comboBox Is Nothing OrElse mbSkipEvent Then Exit Sub
Try
'checks if index that was changed to is > 0 then it toggles the bottom command buttons
ToggleCmdButtons(cboSections.SelectedIndex > 0)
'sets the string msPurpose
msPurpose = "Show Section"
Debug.Print("Im here")
Catch Ex As Exception
Debug.Print("Error Description: " & Ex.Message)
End Try
End Sub