Is there any way to handle multiple events separately with one class? - vb.net

I want to know if there a way around writing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
over and over again.
This is what I tried:
Public Class Ship
Public Property name As String
Public Property image As PictureBox
Public Property length As Integer
Public Property direction As String
Public Property selected As Boolean
Public Property placed As Boolean
Public Property location As Array
Public Sub New(ByVal namep As String, ByVal imagep As PictureBox, ByVal lengthp As Integer, ByVal directionp As String, ByVal selectedp As Boolean, ByVal placedp As Boolean, ByVal locationp As Array)
name = namep
image = imagep
length = lengthp
direction = directionp
selected = selectedp
placed = placedp
location = locationp
End Sub
Private Sub Ship_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.image.MouseMove
'Events here
End Sub
End Class
but I got the errors: Event 'image' cannot be found and End of statement expected

You can use WithEvents here:
Public WithEvents image As PictureBox
And then only
... Handles image.MouseMove
After that, look up AddHandler, too.
AddHandler can do at runtime what the Handles directive does at design time, i.e. it enables you to assign a method to the events of multiple / runtime-created objects.

Related

VB.NET Delegate Function returning Boolean value

I'm using a BackgroundWorker and I need to use a Delegate Function to see if a ListViewItem is checked or not but I keep recieving a cross-thread error. It must be the way I'm writing it. Any help?
Dim delListViewItemChecked As ListViewItemCheckedDelegate = AddressOf ListViewItemChecked
delListViewItemChecked.Invoke(ListViewPhotos, 0)
Private Delegate Function ListViewItemCheckedDelegate(ByVal listView As ListView, ByVal index As Integer) As Boolean
Private Function ListViewItemChecked(ByVal listView As ListView, ByVal index As Integer) As Boolean
If listView.Items(index).Checked = True Then
Return True
Else
Return False
End If
End Function
Try this:
Do not pass the listView as a parameter to ListViewItemCheckedDelegate.
Declare a new delegate instance inside the DoWork handler of your background worker.
This sample seems to work OK:
Private Delegate Function ListViewItemCheckedDelegate(ByVal index As Integer) As Boolean
Private Function ListViewItemChecked(ByVal index As Integer) As Boolean
Return ListView1.Visible
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
bkg1.RunWorkerAsync()
End Sub
Private Sub bkg1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bkg1.DoWork
Dim delListViewItemChecked As New ListViewItemCheckedDelegate(AddressOf ListViewItemChecked)
MsgBox(Me.Invoke(delListViewItemChecked, 3)) ' arbitrary 3
End Sub

Adding items from textbox to a list(of string)

I`m new to vb.net. Looking to find out how to add items into the list. At the moment,its only adding one item. I need it to save many items and must be able to display all items in another textbox. Please help!
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim patients As List(Of String) = New List(Of String)
patients.Add(TextBox1.Text)
TextBox2.Text = patients.Count
End Sub
End Class
Every time you click the button a new copy of the list variable is created and, of course, it is initially empty. You add one item but that's the end of the game.
If you want to preserve the contents of the list, you need to move the List variable at the global class scope
Public Class Form1
Dim patients As List(Of String) = New List(Of String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
patients.Add(TextBox1.Text)
TextBox2.Text = patients.Count
End Sub
.....
End Class
You need to declare and instantiate your list outside of Button Click:
Public Class Form1
Dim patients As New List(Of String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
patients.Add(TextBox1.Text)
TextBox2.Text = patients.Count
End Sub
End Class

List Boxes in VB.NET

I want to manually add two items as "Active" and "Inactive" in a ListBox. When the user selects "Active", i want to get the value "A" and when "Inactive" is selected, i want to get "I".
How do i do this in VB.NET.
Are you using .NET 4? If so, the simplest solution is probably to use Tuple(Of String, String). Create a tuple of ("Active", "A") and another of ("Inactive", "I") and add those to the listbox. Then set the listbox's DisplayMember property to "Item1" and ValueMember to "Item2".
Or you could do the same sort of thing with an anonymous type.
The ListboxItemCollection is of type Object. You can create a custom ListItem like this
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
BindListBox()
End Sub
Private Sub BindListBox()
With ListBox1
.Items.Add(New CustomListItem("Acitve", "A"))
.Items.Add(New CustomListItem("Inactive", "I"))
.DisplayMember = "Text"
End With
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
MsgBox(CType(ListBox1.SelectedItem, CustomListItem).Value)
End Sub
End Class
''Custom ListItem Class
Public Class CustomListItem
Dim _text As String
Dim _value As String
Sub New(ByVal text As String, ByVal value As String)
Me._text = text
Me._value = value
End Sub
Public ReadOnly Property Text() As String
Get
Return _text
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return _value
End Get
End Property
End Class
A simple option
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Debug.Print(ListBox1.Items(ListBox1.SelectedIndex).ToString.Substring(0, 1))
End Sub

VB.NET editing existing that with a form

I have a simple questions that puzzles me. I need a little bit of refreashment with VB as I have been away for a while. I have a form that adds new contacts. New contacts are added by pressing an appropriate button and they appear as an entry in the list on the form. I try now to add an edit button that will edit existing entries. User will select a given entry on the list and press edit button and will be presented with an appropriate form (AddContFrm). Right now it simply adds another entry with the same title. Logic is handled in a class called Contact.vb Here is my code.
Public Class Contact
Public Contact As String
Public Title As String
Public Fname As String
Public Surname As String
Public Address As String
Private myCont As String
Public Property Cont()
Get
Return myCont
End Get
Set(ByVal value)
myCont = Value
End Set
End Property
Public Overrides Function ToString() As String
Return Me.Cont
End Function
Sub NewContact()
FName = frmAddCont.txtFName.ToString
frmStart.lstContact.Items.Add(FName)
frmAddCont.Hide()
End Sub
Public Sub Display()
Dim C As New Contact
'C.Cont = InputBox("Enter a title for this contact.")
C.Cont = frmAddCont.txtTitle.Text
C.Fname = frmAddCont.txtFName.Text
C.Surname = frmAddCont.txtSName.Text
C.Address = frmAddCont.txtAddress.Text
'frmStart.lstContact.Items.Add(C.Cont.ToString)
frmStart.lstContact.Items.Add(C)
End Sub
End Class
AddContFrm
Public Class frmAddCont
Public Class ControlObject
Dim Title As String
Dim FName As String
Dim SName As String
Dim Address As String
Dim TelephoneNumber As Integer
Dim emailAddress As String
Dim Website As String
Dim Photograph As String
End Class
Private Sub btnConfirmAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmAdd.Click
Dim C As New Contact
C.Display()
Me.Hide()
End Sub
Private Sub frmAddCont_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
and frmStart.vb
Public Class frmStart
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
frmAddCont.Show()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
Dim DelCont As Contact
DelCont = Me.lstContact.SelectedItem()
lstContact.Items.Remove(DelCont)
End Sub
Private Sub lstContact_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstContact.SelectedIndexChanged
End Sub
Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
Dim C As Contact
If lstContact.SelectedItem IsNot Nothing Then
C = DirectCast(lstContact.SelectedItem, Contact)
C.Display()
End If
End Sub
End Class
You haven't really added a question but looking at your code it's a bit weird.
If you click Add it will show frmAddCont and then in the confirm button of that form it'll save the data, but if you click Edit it won't show the form and will only add the same data again. I think you're missing a frmAddCont.Show() in your edit button handler.
However, all in all, you're mixing data with GUI too much. The Contact class should know nothing about frmAddCont, rather, the Add and Edit buttons in the main form should show frmAddCont as required (but I would do ShowDialog rather than Show to make it Modal) and if it's in edit mode I'd send in the Contact to be edited to frmAddCont and then when the user press confirm I'd amend/create the Contact as needed and if it's an Add I'd have a method that the main form could call to get out the new Contact.
I think it's fine for the GUI to know about your Contact class, but the Contact class should now know anything about the forms.

How To Report Progress Changed vb.net?

I need to report progress changed. Consider the following code:
Public Class Calculator
Public Event CalculationProgress (ByVal sender As Object, ByVal e As MyCalculationProgressEventArgs)
Public Function Calculate(..)..
' Perform calculation here ...
' Reporting proggress
Dim args As New MyCalculationProgressEventArgs(myobj, myValue)
RaiseEvent CalculationProgress (Me, args)
...
End Class
*** Another class
Private WithEvents calculator As Calculator
Private Function PerformCalculation(ByVal obj As Object) As CalcParams
Dim params As CalcParams = CType(obj, CalcParams)
calculator = GetCalculator()
....
Return params.result = calculator.Calculate
End Function
Private Sub calculationWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
Handles calculationWorker.DoWork
Dim calcResult As MyType = PerformCalculation(CType(e.Argument, MyType ))
e.Result = calcResult
End Sub
Private Sub calculationWorker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _
Handles calculationWorker.ProgressChanged
CType(Parent.Parent, MainWindow).pbcCurrentProgress.Value = e.ProgressPercentage
End Sub
How and where should I subscribe to CalculationProgress event to call
calculationWorker.ReportProgress(MyCalculationProgressEventArgs.Percent)
?
Are you using a BackgroundWorker object here? If so what you want to do is to subscribe to the CalculationProgress event inside of the calculationWorker_DoWork event handler. You didn't post any information on MyType, so I'll assume you'll need to alter my code to get the Calculator instance.
Private Sub calculationWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) _
Handles calculationWorker.DoWork
Dim calcResult As MyType = PerformCalculation(CType(e.Argument, MyType ))
Dim calc = calcResult.Calculator
AddHandler calc.CalculationProgress, AddressOf HandleCalculationProgress
...
RemoveHandler calc.CalculationProgress, AddressOf HandleCalculationProgress
e.Result = calcResult
End Sub
You would do this after your GetCalculator call, and before calling Calculate.