Telerik version of system.windows.text code - vb.net

I want to have a partial class to manage my focus between radtextboxes when a user presses the enter key and I am looking for the telerik interpretation of this line of code tbs(i).KeyDown += New KeyEventHandler(AddressOf textBoxes_KeyDown) Any ideas. Please help.
Partial Public Class MstFileTruck Inherits Form
Private tbs() As Telerik.WinControls.UI.RadTextBox
Public Sub New()
InitializeComponent()
tbs = New Telerik.WinControls.UI.RadTextBox() {txtTruckNumber, txtRegistrationNumber, txtOwnerName}
For i As Integer = 0 To tbs.Length - 1
tbs(i).Tag = i
tbs(i).KeyDown += New KeyEventHandler(AddressOf textBoxes_KeyDown)
' 'tbs(i).IsHandleCreated += New KeyEventArgs(Keys.Enter) '(AddressOf textBoxes_KeyDown)
' tbs(i).RootElement.KeyDownEvent.EventName(textBoxes_KeyDown) '= New KeyEventArgs(AddressOf Telerik.WinControls.UI.RadTextBoxElement.KeyDownEvent.EventName(textBoxes_KeyDown(tbs, RootRadElement.KeyDownEvent))) '(AddressOf textBoxes_KeyDown)
Next
tbs(0).Focus()
End Sub
Private Sub textBoxes_KeyDown(sender As Object, e As KeyEventArgs)
Dim tb As Telerik.WinControls.UI.RadTextBox = TryCast(sender, Telerik.WinControls.UI.RadTextBox)
If tb IsNot Nothing Then
If e.KeyCode = Keys.Enter Then
Dim tag As Integer = CInt(tb.Tag)
If tag = 2 Then
tbs(0).Focus()
Else
tbs(tag + 1).Focus()
End If
End If
End If
End Sub
End Class

I am not quite sure what your code should do. I am not even sure that your event subscription will work, however, here is how to switch the focus between two instances of RadTextBox:
Private Sub RadTextBox_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles RadTextBox1.KeyDown, RadTextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
Dim tb As RadTextBox = DirectCast(sender, RadTextBox)
If tb.Name = "RadTextBox1" Then
RadTextBox2.TextBoxElement.Focus()
Else
RadTextBox1.TextBoxElement.Focus()
End If
End If
End Sub
Another way to subscribe to an event in VB is:
AddHandler RadTextBox1.KeyDown, AddressOf RadTextBox_KeyDown
Private Sub RadTextBox_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
'your code here
End Sub
here is the whole code as it should look like in your .vb file
Imports Telerik.WinControls.UI
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
AddHandler RadTextBox1.KeyDown, AddressOf RadTextBox_KeyDown
End Sub
Private Sub RadTextBox_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles RadTextBox1.KeyDown, RadTextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
Dim tb As RadTextBox = DirectCast(sender, RadTextBox)
If tb.Name = "RadTextBox1" Then
RadTextBox2.TextBoxElement.Focus()
Else
RadTextBox1.TextBoxElement.Focus()
End If
End If
End Sub
End Class

Related

vb.net System.ArgumentOutOfRangeException When Trying to ping

been trying to follow this guide on how to make picture boxes change colour depending on if the ping has been successful or not. I have some test ip's in a CSV file that the program imports
but I keep getting a exception error. I have 3 picture boxes on the page currently defined from picturebox2 - 4
the code for the whole page is below, any suggestions or fixes would be greatly appreciated
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
Imports System.Timers
Public Class Central
Dim pingTable As DataTable = New DataTable()
Dim ipAddress As List(Of String) = New List(Of String)
Dim pictureBoxList As List(Of PictureBox) = New List(Of PictureBox)
Dim timer As Timers.Timer
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
timer = New Timers.Timer
timer.Interval = 20000
timer.Enabled = True
AddHandler timer.Elapsed, AddressOf OnElapsedTime
End Sub
Private Sub OnElapsedTime(ByVal sender As Object, ByVal e As ElapsedEventArgs)
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub FillPingTable()
pingTable.Columns.Add("ip", GetType(String))
pingTable.Columns.Add("picturebox", GetType(String))
pingTable.Rows.Add()
For i As Integer = 0 To ipAddress.Count - 1
pingTable.Rows.Add(ipAddress(i), pictureBoxList(i))
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Hide()
Scot.Show()
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Hide()
Home.Show()
End Sub
Private Sub central_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using reader = New StreamReader("A:\IpAddress.csv")
While Not reader.EndOfStream
Dim line = reader.ReadLine
Dim values = line.Split(ChrW(10))
ipAddress.Add(values(0))
End While
For i As Integer = 1 To 2
pictureBoxList.Add(CType(Controls.Find("PictureBox" & i, True)(0), PictureBox))
FillPingTable()
BackgroundWorker1.RunWorkerAsync()
Next
End Using
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Thread.Sleep(500)
Parallel.For(0, ipAddress.Count(), Sub(i, loopState)
Dim ping As New Ping()
Dim pingReply As PingReply = ping.Send(ipAddress(i).ToString())
Me.BeginInvoke(CType(Sub()
pictureBoxList(i).SizeMode = PictureBoxSizeMode.Zoom
pictureBoxList(i).BackColor = If(pingReply.Status = IPStatus.Success, Color.Green, Color.Red)
End Sub, Action))
End Sub)
End Sub
End Class

DataGridView right click event and pass-through of parameters to sub

I read a lot of things here in the forum, but I can't find a solution for my problem.
I have a DataGridView with a ContextMenu.
My aim is to call a function from the context menu and pass through parameters e.g. linenumber of selected dgv row.
Here is my code, that contains a ContextMenu, but how I could pass-through some parameters to a function?
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenu
m.MenuItems.Add(New MenuItem("Sub1"))
m.MenuItems.Add(New MenuItem("Sub2"))
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
EDIT
Now I have got a solution that works, but I think it is not the best solution and I can do a lot of improvement.
Maybe it would be possible to code custom events, that can pass through some datas of the gridview. I hope somebody is interested to give some input to improve the following (working) code to look something like professional.
Imports System
Imports System.IO
Public Class Form1
Public gpath As String = "D:\kvt.txt"
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file = System.IO.File.ReadAllLines("d:\kvt.txt")
Dim dt As New DataTable
dt.Columns.Add("Name")
For Each line As String In file
dt.Rows.Add(line)
Next
DataGridView1.DataSource = dt
DataGridView1.Show()
End Sub
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim cMenu As New ContextMenuStrip
Dim MenuItemClone As New System.Windows.Forms.ToolStripMenuItem
MenuItemClone.Text = "Clone"
cMenu.Items.Add(MenuItemClone)
If e.Button = MouseButtons.Right Then
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
cMenu.Show(DataGridView1, New Point(e.X, e.Y))
AddHandler MenuItemClone.Click, AddressOf CloneRepo
End If
End Sub
Private Sub CloneRepo(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SelectedName As String = DataGridView1("Name", DataGridView1.CurrentCell.RowIndex).FormattedValue
End Sub
End Class
Here's an example of how you can right-click on a cell in a DataGridView and then perform an action relative to that cell when you click a menu item:
Private lastClickedCell As DataGridViewCell
Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
If e.ColumnIndex >= 0 AndAlso
e.RowIndex >= 0 Then
lastClickedCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
End If
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right AndAlso
DataGridView1.HitTest(e.X, e.Y).Type = DataGridViewHitTestType.Cell Then
'Display the menu when right-clicking on a cell.
ContextMenuStrip1.Show(DataGridView1, e.Location)
End If
End Sub
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearToolStripMenuItem.Click
'Clear the cell that was right-clicked.
lastClickedCell.Value = Nothing
End Sub
The ContextMenuStrip was created in the designer for this example. I would recommend doing that in your case too, even if you need to choose items dynamically. You can clear the menu and add and/or remove items in the CellMouseClick or MouseClick event handlers of the grid, or the Opening event handler of the menu.
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim col As New DataGridTextBoxColumn
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenuStrip
col.TextBox.ContextMenuStrip = m
Dim tsp As New ToolStripMenuItem("Sub1", Nothing, New EventHandler(AddressOf TestMessage))
Dim tsp1 As New ToolStripMenuItem("Sub2", Nothing, New EventHandler(AddressOf TestMessage))
m.Name = "Menulist"
m.Items.Add(tsp)
m.Items.Add(tsp1)
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub TestMessage()
MessageBox.Show("Clicked")
End Sub
try this and use 'Tag':
Dim currentMouseOverRow As Integer
Structure MyStructure
Public x As Integer
Public y As Integer
End Structure
Private Sub DataGridView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick
Dim Mystruct As MyStructure
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim m As New System.Windows.Forms.ContextMenuStrip
Dim MymenuToolStripMenuItem1 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem1.Text = "menu1"
AddHandler MymenuToolStripMenuItem1.Click, AddressOf MymenuToolStripMenuItem1_Click
m.Items.Add(MymenuToolStripMenuItem1)
Dim MymenuToolStripMenuItem2 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem2.Text = "menu2"
AddHandler MymenuToolStripMenuItem2.Click, AddressOf MymenuToolStripMenuItem2_Click
m.Items.Add(MymenuToolStripMenuItem2)
Mystruct.x = e.X
Mystruct.x = e.X
MymenuToolStripMenuItem2.Tag = Mystruct
currentMouseOverRow = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub MymenuToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("click Menu1:" & currentMouseOverRow)
End Sub
Private Sub MymenuToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Mystruct As MyStructure
Mystruct = CType(CType(sender, System.Windows.Forms.ToolStripMenuItem).Tag, MyStructure)
MessageBox.Show("click Menu2:" & currentMouseOverRow & " x:" & Mystruct.x & " y:" & Mystruct.y)
End Sub

Late Binding Issue with BackgroundWorker in VB.Net

I am running a BackgroundWorker, and want to report its progress. In the example below I create a test list which the BackgroundWorker then iterates through. The problem lies in the line 'sender.ReportProgress(i)'. If I have Option Strict on, it does not like my use of 'i' due to Late Binding issues. Is there any alternative way to code this and avoid that issue?
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' Configuring for Background Workers
Control.CheckForIllegalCrossThreadCalls = False
Dim MyList As New List(Of String)
For a As Integer = 0 To 100
MyList.Add(CStr(a))
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim bgw As New System.ComponentModel.BackgroundWorker
bgw.WorkerReportsProgress = True
bgw.WorkerSupportsCancellation = True
AddHandler bgw.DoWork, AddressOf bgw_DoWork
' I create a BackgroundWorker here rather than add one in the toolbox so that I can specify the Handler and use different Handler routines for different part of a large program.
Button1.Enabled = False
Dim progress As New Progress(bgw)
progress.ShowDialog()
Button1.Enabled = True
End Sub
Private Sub bgw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs)
For i = 0 To MyList.Count -1
Label1.Text = MyList(i)
sender.ReportProgress(i)
System.Threading.Thread.Sleep(200)
Label1.Refresh()
Next
End Sub
End Class
Public Class Progress
Private WithEvents _BGW As System.ComponentModel.BackgroundWorker
Public Sub New(ByVal BGW As System.ComponentModel.BackgroundWorker)
_BGW = BGW
InitializeComponent()
End Sub
Private Sub frmProgress_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
If Not IsNothing(_BGW) Then
_BGW.RunWorkerAsync()
End If
End Sub
Private Sub _BGW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles _BGW.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = e.ProgressPercentage
End Sub
Private Sub _BGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles _BGW.RunWorkerCompleted
Me.Close()
End Sub
End Class
CType(sender, BackgroundWorker).ReportProgress(i)
Also, if you want to do multiple actions with it, then create a local reference variable like this:
Private Sub bgw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs)
Dim bgw As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
' ... now you can use "bgw" multiple times below instead of casting each time ...
For i = 0 To MyList.Count -1
Label1.Text = MyList(i)
bgw.ReportProgress(i)
bgw.SomethingElse()
bgw.MoreStuff()
System.Threading.Thread.Sleep(200)
Label1.Refresh()
Next
End Sub
Obviously this isn't necessary in your case, just an FYI...

VB 2010 Form Show

i currently have multiple forms (around 30 forms) and i am switching between forms. The Main form (Form1) has 29 buttons and each button will take me to the respective form number (example: button3 = form3, button20=form20, etc).
I understand that I can use the code:
me.hide
form1.show
I want a method to pass the form name dynamically, something along the lines of:
me.controls(FormName).show
Is this possible?
Create a new project with three forms (Form1, Form2, and Form3). Put two buttons on Form1 (named Button2 and Button3), then place the following source code in Form1:
Option Strict On
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Call FormFromButton(DirectCast(sender, Button))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Call FormFromButton(DirectCast(sender, Button))
End Sub
Public Sub FormFromButton(btn As Button)
Dim i As Integer = CInt(btn.Name.Substring(6)) 'Get number after "button" (6 characters)
Dim f As Form = GetForm("Form" & i.ToString)
f.Show()
f.Activate()
End Sub
Public Function GetForm(formClassName As String) As Form
'see if it is already instanced
For Each f As Form In My.Application.OpenForms
If f.GetType.Name = formClassName Then Return f
Next f
'create new instance
Dim strFullName As String = Me.GetType.Namespace & "." & formClassName
Dim o As Object = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(strFullName)
Dim frm As Form = DirectCast(o, Form)
Return frm
End Function
End Class
Myself created 4 forms one is parent another 3(Form3,Form4,Form5) is child and i was created 3 buttons in parent form and that button Text is Form3,Form4,Form5
Imports System
Imports System.Reflection
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is Button Then
Dim btn As Button
btn = DirectCast(ctrl, Button)
AddHandler btn.Click, AddressOf Me.buttonclick
End If
Next
End Sub
Private Sub buttonclick(sender As Object, e As EventArgs)
Dim frmname As Button = DirectCast(sender, Button)
Dim frmAssembly As Assembly = Assembly.LoadFile(Application.ExecutablePath)
For Each type As Type In frmAssembly.GetTypes
If type.BaseType = GetType(Form) Then
If (type.Name = frmname.Text) Then
Dim frmshow As Form = DirectCast(frmAssembly.CreateInstance(type.ToString()), Form)
For Each frm As Form In Me.MdiChildren
frm.Close()
Next
frmshow.Show()
End If
End If
Next
End Sub
End Class
Private Sub ButtonClick(ByVal sender As Object, e As System.EventArgs)
Dim btn As Button = DirectCast(sender, Button)
Dim formname As String = "form" & btn.Name(btn.Name.Length - 1)
Dim frm As Form = GetForm(formname)
frm.Show()
End Sub
Private Function GetForm(ByVal Formname As String) As Form
Dim t As Type = Type.GetType(Formname) ', True, True)
If t Is Nothing Then
Dim Fullname As String = Application.ProductName & "." & Formname
t = Type.GetType(Fullname, True, True)
End If
Return CType(Activator.CreateInstance(t), Form)
End Function
Private Sub AddHandlers()
AddHandler Button1.Click, AddressOf ButtonClick
AddHandler Button2.Click, AddressOf ButtonClick
AddHandler Button3.Click, AddressOf ButtonClick
AddHandler Button4.Click, AddressOf ButtonClick
End Sub
Private Sub RemoveHandlers()
RemoveHandler Button1.Click, AddressOf ButtonClick
RemoveHandler Button2.Click, AddressOf ButtonClick
RemoveHandler Button3.Click, AddressOf ButtonClick
RemoveHandler Button4.Click, AddressOf ButtonClick
End Sub
Private Sub Form2_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated
AddHandlers()
End Sub
Private Sub Form2_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
RemoveHandlers()
End Sub

vb2012 textbox backcolor does't change using thread

I wrote very simple thread example.
Make normal form1 and drop 1 textbox
run thread work on form load
thread change a textbox backcolor looks like switch on/off
But, it doesn't work.....
Can you tell me why doesn't work??
see my source.
=====================================================================
Imports System.Threading
Public Class Monitor
Public wObj As Worker = New Worker()
Public MyThread As Thread = New Thread(AddressOf wObj.DoWork)
Public Sub ChangeTBColor(pOption As Integer)
If pOption = 1 Then
tb1.BackColor = Color.Aqua
Else
tb1.BackColor = Color.Red
End If
End Sub
Private Sub Monitor_Load(sender As Object, e As EventArgs) Handles Me.Load
MyThread.Start()
Console.WriteLine("Running OrgThread..")
Console.WriteLine("Stop running")
End Sub
Private Sub BtnThreadStop_Click(sender As Object, e As EventArgs) Handles BtnThreadStop.Click
Me.wObj.RequestStop()
End Sub
End Class
Public Class Worker
Private LoopStop As Boolean = True
Public Sub DoWork()
Console.WriteLine("User Thread Start!")
Dim iTemp As Integer = 0
While (LoopStop)
Monitor.ChangeTBColor(iTemp Mod 2)
iTemp = iTemp + 1
Thread.Sleep(500)
End While
Console.WriteLine("User Thread End.!")
End Sub
Public Sub RequestStop()
LoopStop = False
End Sub
End Class
As already mentioned, your starting a new thread for your work, the issue is your trying to change the color for a control that need invoking. With this said, we need a delegate for when the control needs to be invoked... In my example, I used one class that handles this all and works great. Also please make sure to import System.ComponentModel because this is needed for the BackgroundWorker... I used the background worker as it takes all the heavy lifting off you would need...
Imports System.ComponentModel
Imports System.Threading
Public Class Monitor
Delegate Sub SetColor(ByVal clr As Integer) 'Your delegate..
Private WithEvents bw As New BackgroundWorker
Public Sub ChangeTBColor(pOption As Integer)
If Me.tb1.InvokeRequired Then 'Invoke if required...
Dim d As New SetColor(AddressOf ChangeTBColor) 'Your delegate...
Me.Invoke(d, New Object() {pOption})
Else
If pOption = 1 Then
tb1.BackColor = Color.Aqua
Else
tb1.BackColor = Color.Red
End If
End If
End Sub
Private Sub Monitor_Load(sender As Object, e As EventArgs) Handles Me.Load
bw.WorkerSupportsCancellation = True
Console.WriteLine("Running OrgThread..")
bw.RunWorkerAsync()
End Sub
Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
Dim iTemp As Integer = 0
Dim LoopStop As Boolean = True
Console.WriteLine("User Thread Start!")
While (LoopStop)
If Not (bw.CancellationPending) Then
ChangeTBColor(iTemp Mod 2)
iTemp = iTemp + 1
Thread.Sleep(500)
Else
e.Cancel = True
LoopStop = False
End If
End While
End Sub
Private Sub bw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
Console.WriteLine("User Thread End.!")
End Sub
Private Sub BtnThreadStop_Click(sender As Object, e As EventArgs) Handles BtnThreadStop.Click
If bw.IsBusy Then
bw.CancelAsync()
Else
Console.WriteLine("Running OrgThread..")
bw.RunWorkerAsync()
End If
End Sub
End Class
Here's my screenshot of my test... This is tried and tested. Please be sure to vote if this helps you!