How to Pass MethodName as Parameter of a Procedure in VBNET - vb.net

I want to create a Procedure that its parameter is also a procedure. Is it possible?
I created some procedures to be used as parameters below:
Private Sub Jump(xStr as string)
Msgbox xStr & " is jumping."
End Sub
Private Sub Run(xStr as string)
Msgbox xStr & " is jumping."
End Sub
this procedure should call the procedure above:
Private Sub ExecuteProcedure(?, StringParameter) '- i do not know what to put in there
? ' - name of the procedure with parameter
End Sub
usage:
ExecuteProcedure(Jump, "StringName")
ExecuteProcedure(Run, "StringName")

I believe the following code is an example for what you need.
Public Delegate Sub TestDelegate(ByVal result As TestResult)
Private Sub RunTest(ByVal testFunction As TestDelegate)
Dim result As New TestResult
result.startTime = DateTime.Now
testFunction(result)
result.endTime = DateTime.Now
End Sub
Private Sub MenuItemStartTests_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemStartTests.Click
Debug.WriteLine("Starting Tests...")
Debug.WriteLine("")
'==================================
' Add Calls to Test Modules Here
RunTest(AddressOf Test1)
RunTest(AddressOf Test2)
'==================================
Debug.WriteLine("")
Debug.WriteLine("Tests Completed")
End Sub
The entire article can be found at http://dotnetref.blogspot.com/2007/07/passing-function-by-reference-in-vbnet.html
Hope this helps.

Related

How to Save Textboxt.Text as file name?

What's wrong with this code?
I need to add textbox13.text (the value of it is in number) as the file name and how can I add an option which checks if the file already exists if so show an option saying replace or cancel when I press my save button.
So far here is the code :
Dim i As Integer = 0
Dim filepath As String = IO.Path.Combine("D:\Logs", Textbox13.Text + i.ToString() + ".txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(TextBox13.Text)
sw.WriteLine(TextBox1.Text)
sw.WriteLine(TextBox2.Text)
sw.WriteLine(TextBox3.Text)
sw.WriteLine(TextBox4.Text)
sw.WriteLine(TextBox5.Text)
sw.WriteLine(TextBox7.Text)
sw.WriteLine(TextBox9.Text)
sw.WriteLine(TextBox10.Text)
sw.WriteLine(TextBox11.Text)
sw.WriteLine(TextBox12.Text)
This is from Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Form2.WriteTextBoxTextToLabel(TextBox1.Text)
Form2.WriteTextBoxTextToTextbox(TextBox1.Text)
End Sub
This is from form2
Public Sub WriteTextBoxTextToLabel(ByVal Txt As String)
lblPD.Text = Txt
End Sub
Public Sub WriteTextBoxTextToTextbox(ByVal Txt As String)
TextBox13.Text = Txt
End Sub
Private Sub TextBox13_TextChanged(sender As Object, e As EventArgs) Handles TextBox13.TextChanged
TextBox13.Text = lblPD.Text
End Sub
You can add the following logic before creating the StreamWriter:
if system.io.file.exists(filepath) then
' The file exists
else
' The file does not exist
end if

Overload VB.NET event?

In my VB.NET class I have some code like this:
Public Class barClass
Private Function foo(data as string)
msgbox("Data is a string: " & data)
End Function
Private Function foo(data as integer)
msgbox("Data is an integer: " & data
End Function
End Class
Which obviously lets you pass foo a string or integer.
I figured I could do the same for events, so I try:
Public Event FooRaised(data as string)
Public Event FooRaised(data as integer)
Which I assume would let me raise the event by passing it whatever data I get from foo but I get an error, saying I can't do that (that FooRaised has already been declared).
How do I achieve this?
Declare a single event using an Object parameter, then check the type to process it:
Public Class Form1
Public Event Foo(o As Object)
Sub FooHandler(o As Object) Handles Me.Foo
If o.GetType Is GetType(Integer) Then
Dim i As Integer = DirectCast(o, Integer)
i += 1 'add one to the integer value'
MsgBox(i.ToString)
ElseIf o.GetType Is GetType(String) Then
Dim s As String = DirectCast(o, String)
s &= "!!" 'append exclamation marks'
MsgBox(s)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RaiseEvent Foo(21)
RaiseEvent Foo("a string value")
End Sub
End Class

how to link dropdown menu to other class

i have a problem where i have to link dropdown menu to other class, which the class is sqlcommand
so my code a bit much like this
Form1.vb
Public Class Input
Dim CallSQL As New SQL Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Visible = True
If ListBox1.SelectedValue = "A" Then
-------"I DONT KNOW HOW TO COMMAND HERE "--
End If
If ListBox1.SelectedValue = "B" Then
-------"I DONT KNOW HOW TO COMMAND HERE "---------
End If
End Sub
End Class
and i need to match the dropdown from here
SQL.vb
Public Class SQL
Private Sub GetRoadDataFromDatabase(station)
ExecuteSqlCommand("exec '" & station & "', 'A'", "TableA")
End Sub
Public Sub GettrainDataFromDatabase(station)
ExecuteSqlCommand("exec '" & station & "', 'B'", "TableB")
End Sub
so when user choose A, executesql data for road, and when choose B execute data for train. please help me.this suppose to be a simple task. but since im new in vb.bet i cant figure it out
You want to execute GetRoadDataFromDatabase if user selects option 'A' and GetTrainDataFromDatabase if user selects B. Simply create instance of SQL class outside of IF/ELSE statements and call relevant method in IF/ELSE:
Public Class Input
Dim CallSQL As New SQL Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Visible = True
Dim sql AS SQL =new SQL() 'Please check this if it is valid VB.Net statement
If ListBox1.SelectedValue = "A" Then
'Supposing you have got station already
sql.GetRoadDataFromDatabase(station)
End If
If ListBox1.SelectedValue = "B" Then
'Supposing you have got station already
sql.GettrainDataFromDatabase(station)
End If
End Sub
End Class
EDIT:- Not making methods public
As you have stated that you don't want to make the two functions public, an option is to write a gateway function to accept parameters and then call the desired private method.
Public Class SQL
Private Sub GetRoadDataFromDatabase(station)
ExecuteSqlCommand("exec '" & station & "', 'A'", "TableA")
End Sub
'THOUGH YOUR THIS FUNCTION IS PUBLIC IN QUESTION
Private Sub GettrainDataFromDatabase(station)
ExecuteSqlCommand("exec '" & station & "', 'B'", "TableB")
End Sub
Public Sub CallDBFunction(station as string, code as string)
If code == "A" Then
GetRoadDataFromDatabase(station)
Else
GetTrainDataFromDatabse(station)
End If
End Sub
End Class

how to assign value to NodeLabelEditEventArgs variable

i created this sub
Sub CreateNewNode(tree As TreeView, e As NodeLabelEditEventArgs)
Dim nodeTxt As String
nodeTxt = e.Label
If e.Node.Level = 0 Then
Dim obj_carsType As New Cls_carsType
Dim Entity As New tblcarsType
Entity.Type = nodeTxt
obj_carsType .Insert(Entity)
Dim q = (From i In obj_logsType.Fill Select i.ID).Last
e.CancelEdit = True
tree.Nodes.Remove(e.Node)
tree.Nodes.Add(nodeTxt & " : " & q.tostring)
end sub
Sub TreeView1_NodeMouseClick()
e.Node.ContextMenuStrip =ContextMenuStrip1
end sub
Private Sub NEWITEmToolStripMenuItem_Click()
end sub
in last sub need to call first sub. also in last sub if user click on NEWITEM i must call the first sub how can i do it?? please help me
I think you need something like this:
Private Sub NEWITEmToolStripMenuItem_Click(byval sender as object, byval e as eventargs)
CreateNewNode(ctype(sender, TreeView), ctype(e,NodeLabelEditEventArgs))
end sub

Change a label text with the forms name in a string eg. String1.label1.text

I am trying to create a Function that does everything automatically. Here is my current code:
Public Sub IncrementValueBeta(SlideDescription As String, SlideNumber As Integer, FormName As String)
ChangeSlide (SlideNumber)
MsgBox ("Test: " + SlideDescription)
AddClicks = FormName.ClickedTimes.Text + 1
FormName.ClickedTimes.Text = AddClicks
End Sub
This will add a number to the value but I am trying to make the code more concise without having to do if FormName = "Slide1" a 1000 times as it is a huge questionnaire.
The user will type "FormName" e.g., "Form1". In the code, it will use it like FormName.ClickedTimes.Caption = AddClicks so in the slide if the slide was 25 clicks it would be 26 that's already working but only if I do Slide3 not FormName is there a way I can do this? If you know how, can you help me because it will be a real pain if I have to do If bah = "bah" then elseif bah = "bah" then 1000 times.
This will basically Change the text of the Form label, to Eg, the user has clicked yes i like sports, the code will load the module/class and change label1.text to +1 clicks and it will change label2.text to "Question 2" but it doesn't know what form it is so it will use the text in FormName that was given with the arguments to find out what form it is editing. thats what im trying to accomplish here
In short, i just want it to find the form from FormName and View FormName.Label1.text = "" as Form1.Label1.text = ""
*Assuming there is only one instance of the desired Form, try something like this:
Public Sub IncrementValueBeta(SlideDescription As String, SlideNumber As Integer, FormName As String)
ChangeSlide(SlideNumber)
Dim frmTarget As Form = Nothing
For Each frm As Form In Application.OpenForms
If frm.Name.ToUpper = FormName.ToUpper Then
frmTarget = frm
Exit For
End If
Next
If Not IsNothing(frmTarget) Then
Dim matches() As Control = frmTarget.Controls.Find("ClickedTimes", True)
If matches.Length > 0 Then
AddClicks = matches(0).Text + 1
matches(0).Text = AddClicks
End If
End If
End Sub
I would also go with the way of using dictionaries.
Public Class Form1
Private slides As New Dictionary(Of Integer, String)
Private currentSlideNumber As Integer
Private currentSlideDescription As String
Public Sub IncrementByClick()
currentSlideDescription = slides(currentSlideNumber + 1)
currentSlideNumber += 1
ChangeSlide(currentSlideDescription)
End Sub
Public Sub ChangeSlide(ByVal slideDescription As String)
currentSlideNumber = SelectSlideNumberByDesc(slideDescription)
currentSlideDescription = slides(currentSlideNumber)
MessageBox.Show("Successfully changed the slide to slide no. " & currentSlideNumber)
End Sub
Private Function SelectSlideNumberByDesc(ByVal slideDesc As String)
Dim slideNumber As Integer
For Each slide In slides
If slide.Value = slideDesc Then
slideNumber = slide.Key
Exit For
End If
Next
Return slideNumber
End Function
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
slides.Add(1, "SLIDE_ONE")
slides.Add(2, "SLIDE_TWO")
slides.Add(3, "SLIDE_THREE")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ChangeSlide(TextBox1.Text)
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
IncrementByClick()
End Sub
End Class
With by clicking button1, the slide will change according to the slide description the user have entered in the textbox.
By clicking btnNext, next slide will load accordingly.
OO way is way better but this should be enough to show it.