Mainform VB.Net:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.tsBasket = New System.Windows.Forms.ToolStrip()
Me.tsiFruit = New System.Windows.Forms.ToolStripDropDownButton()
Me.tsBasket.SuspendLayout()
Me.SuspendLayout()
'
'tsBasket
'
Me.tsBasket.Dock = System.Windows.Forms.DockStyle.None
Me.tsBasket.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.tsBasket.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.tsiFruit})
Me.tsBasket.Location = New System.Drawing.Point(355, 213)
Me.tsBasket.Name = "tsBasket"
Me.tsBasket.Size = New System.Drawing.Size(121, 25)
Me.tsBasket.TabIndex = 5
'
'tsiFruit
'
Me.tsiFruit.ImageTransparentColor = System.Drawing.Color.Magenta
Me.tsiFruit.Name = "tsiFruit"
Me.tsiFruit.Size = New System.Drawing.Size(87, 22)
Me.tsiFruit.Text = "add fruit"
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.tsBasket)
Me.Name = "Form1"
Me.Text = "Form1"
Me.tsBasket.ResumeLayout(False)
Me.tsBasket.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents tsBasket As ToolStrip
Friend WithEvents tsiFruit As ToolStripDropDownButton
End Class
Form Load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool()
men.Text = "showmeplease"
men.Image = Nothing
men.NewProperty = "BO"
Dim men2 As New TestTool()
men2.Text = "showmeplease2"
men2.Image = Nothing
men2.NewProperty = "BO2"
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Private Sub tsiType_Click(sender As System.Object, e As System.EventArgs)
Dim MenuItem As TestTool = DirectCast(sender, TestTool)
MessageBox.Show(MenuItem.NewProperty & " " & MenuItem.Text)
End Sub
Custom class:
Public Class TestTool
Inherits ToolStripItem
Private newPropertyValue As String
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
Sub New()
' This call is required by the designer.
' InitializeComponent()
End Sub
End Class
On my custom class/Usercontrol I am getting :
The designer must create an instance of type 'System.Windows.Forms.ToolStripItem' but it cannot because the type is declared as abstract. and I am not seeing the text appear in the menu items, but the click event works fine.
Is this the correct way to extend(Inherit using OO) a ToolMenuStrip so that I can have a Display value and a Member value, I want to be able to store an object without using .Tag.
Edit:
I am getting when trying to have nested menus:
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.ToolStripMenuItem' to type 'WindowsApp1.TestTool'.'
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool()
men.Text = "showmeplease"
men.Image = Nothing
men.NewProperty = "BO"
Dim men2 As New TestTool()
men2.Text = "showmeplease2"
men2.Image = Nothing
men2.NewProperty = "BO2"
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
Dim TypeMenuItem As TestTool = men.DropDownItems.Add("hh")
For Each mInfo As String In Moreinfo
TypeMenuItem.DropDownItems.Add(mInfo, Nothing, AddressOf tsiType_Click)
Next
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Private p_Moreinfo As List(Of String)
Public Property Moreinfo() As List(Of String)
Get
Dim test As New List(Of String)
test.Add("A")
test.Add("B")
Return test
End Get
Set(ByVal value As List(Of String))
p_Moreinfo = value
End Set
End Property
If you enable the Option Strict check (you should), you will find an error with the line below in the Form1_Load event:
' Error: Option Strict On disallows implicit conversions from ToolStrinpItem
' to TestTool.
Dim TypeMenuItem As TestTool = men.DropDownItems.Add("hh")
Because the .DropDownItems.Add(String) overload returns a ToolStripItem and not an object of type TestTool. The .DropDownItems don't inherit the type of the owner item.
' Compiles.
Dim TypeMenuItem As ToolStripItem = men.DropDownItems.Add("hh")
' Compiles.
Dim TypeMenuItem As ToolStripMenuItem = DirectCast(men.DropDownItems.Add("hh"), ToolStripMenuItem)
' Throws System.InvalidCastException.
Dim TypeMenuItem As TestTool = DirectCast(men.DropDownItems.Add("hh"), TestTool)
So, the code in Load event should be like:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim men As New TestTool With {
.Text = "showmeplease",
.NewProperty = "BO"
}
Dim men2 As New TestTool With {
.Text = "showmeplease2",
.NewProperty = "BO2"
}
tsiFruit.DropDownItems.Add(men)
tsiFruit.DropDownItems.Add(men2)
Dim TypeMenuItem As New TestTool() With {.NewProperty = "hh", .Text = "SomeText"}
men.DropDownItems.Add(TypeMenuItem)
For Each mInfo As String In Moreinfo
Dim item = New TestTool With {.NewProperty = mInfo, .Text = "SomeText"}
AddHandler item.Click, AddressOf tsiType_Click
TypeMenuItem.DropDownItems.Add(item)
Next
AddHandler men.Click, AddressOf tsiType_Click
AddHandler men2.Click, AddressOf tsiType_Click
End Sub
Likewise, to avoid throwing exceptions in the tsiType_Click event, just in case:
Private Sub tsiType_Click(sender As Object, e As EventArgs)
Dim item = TryCast(sender, TestTool)
If item IsNot Nothing Then
MessageBox.Show($"{item.NewProperty} {item.Text}")
Else
MessageBox.Show(DirectCast(sender, ToolStripItem).Text)
End If
End Sub
I believe you have modified the TestTool class as #jmcilhinney commented to something like:
Public Class TestTool
Inherits ToolStripMenuItem
Sub New()
MyBase.New
End Sub
Public Property NewProperty As String
End Class
The DataGridViewComboBoxColumn control can be difficult to work with. I've been fighting various permutations of this code for two long days, so I've decided to throw in the towel and seek some assistance.
The latest incarnation of weirdness is a ComboBox event handler that fires an increasing number of times for a single user action. Oddly, the rate of increase is an exact doubling of the count just preceding (i.e. 1, 2, 4, 8, 16, 32, 64 etc.)
To start things off, I'll explain what I'm trying to accomplish and also clarify some terminology.
I have a Dictionary(Of Integer, String). In my domain rules, I'm calling its Key property Channel and its Value property Label. I'm mapping each KeyValuePair to a third String value called Target. The Dictionary(Of Integer, String) items are fixed—they exist as a visual aid for the user, so he can easily select the Target from a List(Of String).
I've settled on a DataGridView control to provide this functionality. I'm using three columns, like so:
Note that already-mapped Target list items are displayed in a nearly-invisible color, so as to discourage the user from trying to use them again. (This is where the event handler problem comes in—when an already-mapped Target is selected for mapping to a different Label.)
I'm including my full code base below, but for a quick look here's the event handler that repeats:
Private Sub ComboBox_SelectionChangeCommitted(Sender As ComboBox, e As EventArgs)
' '
' Look for other labels that have already been mapped to this target '
' '
If Me.OtherTargetCells.Any(Function(Cell) Cell.FormattedValue = Sender.Text) Then
If Me.IsInteractiveChange Then
MsgBox("Target [] is already mapped to Label []. If you want to map Target [] to Label [], you must first set Label [] to [Not mapped].", MsgBoxStyle.Exclamation, Me.DataGridView.FindForm.Text)
Me.IsInteractiveChange = False
Sender.SelectedIndex = 0
Me.IsInteractiveChange = True
End If
End If
End Sub
And here's how I'm wiring it all up:
Public Sub New()
Task.Run(Sub()
Dim oHandler As DataGridViewEditingControlShowingEventHandler
While Me.DataGridView Is Nothing
End While
oHandler = New DataGridViewEditingControlShowingEventHandler(AddressOf DataGridView_EditingControlShowing)
RemoveHandler Me.DataGridView.EditingControlShowing, oHandler
AddHandler Me.DataGridView.EditingControlShowing, oHandler
End Sub)
End Sub
Private Sub DataGridView_EditingControlShowing(Sender As DataGridView, e As DataGridViewEditingControlShowingEventArgs)
Dim oComboBox As ComboBox
If TypeOf e.Control Is ComboBox Then
oComboBox = e.Control
oComboBox.DrawMode = DrawMode.OwnerDrawFixed
RemoveHandler oComboBox.DrawItem, New DrawItemEventHandler(AddressOf ComboBox_DrawItem)
AddHandler oComboBox.DrawItem, New DrawItemEventHandler(AddressOf ComboBox_DrawItem)
RemoveHandler oComboBox.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
AddHandler oComboBox.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
End If
End Sub
The repeat count multiplies when I select an already-mapped Target from a different list than previously (e.g. selecting twice from SCC doesn't increase the count, but selecting from SCC and then Scale does.)
I've tried many, many, many possible solutions for this—too many to list here and most of which I just don't remember—but none with any success.
What can I do to constrain the handler to fire only once for each selection change?
Mapping.TargetsColumn.vb
Namespace Mapping
Public Class TargetsColumn
Inherits DataGridViewComboBoxColumn
Public Sub New()
Task.Run(Sub()
Dim oHandler As DataGridViewEditingControlShowingEventHandler
While Me.DataGridView Is Nothing
End While
oHandler = New DataGridViewEditingControlShowingEventHandler(AddressOf DataGridView_EditingControlShowing)
RemoveHandler Me.DataGridView.EditingControlShowing, oHandler
AddHandler Me.DataGridView.EditingControlShowing, oHandler
End Sub)
End Sub
Private Sub DataGridView_EditingControlShowing(Sender As DataGridView, e As DataGridViewEditingControlShowingEventArgs)
Dim oComboBox As ComboBox
If TypeOf e.Control Is ComboBox Then
oComboBox = e.Control
oComboBox.DrawMode = DrawMode.OwnerDrawFixed
RemoveHandler oComboBox.DrawItem, New DrawItemEventHandler(AddressOf ComboBox_DrawItem)
AddHandler oComboBox.DrawItem, New DrawItemEventHandler(AddressOf ComboBox_DrawItem)
RemoveHandler oComboBox.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
AddHandler oComboBox.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
End If
End Sub
Private Sub ComboBox_DrawItem(Sender As ComboBox, e As DrawItemEventArgs)
Dim sThisTarget As String
Dim oForeColor As Color
Dim _
iSeparatorBottom,
iSeparatorRight,
iSeparatorLeft As Integer
Dim _
oSeparatorStart,
oSeparatorStop As Point
sThisTarget = DirectCast(Me.Items(e.Index), Target).Value
iSeparatorBottom = e.Bounds.Bottom - 2
iSeparatorRight = e.Bounds.Right
iSeparatorLeft = e.Bounds.Left
e.DrawBackground()
If e.Index = 0 Then
oSeparatorStart = New Point(iSeparatorLeft, iSeparatorBottom)
oSeparatorStop = New Point(iSeparatorRight, iSeparatorBottom)
oForeColor = SystemColors.HotTrack
e.Graphics.FillRectangle(SystemBrushes.Control, e.Bounds)
e.Graphics.DrawLine(SystemPens.ControlDark, oSeparatorStart, oSeparatorStop)
Else
If Me.OtherTargets.Contains(sThisTarget) Then
oForeColor = SystemColors.ControlLight
Else
oForeColor = e.ForeColor
End If
End If
Using oBrush As New SolidBrush(oForeColor)
e.Graphics.DrawString(sThisTarget, e.Font, oBrush, e.Bounds)
End Using
If e.State.HasFlag(DrawItemState.Focus) Then e.DrawFocusRectangle()
Me.DataGridView.FindForm.Text = sThisTarget
End Sub
Private Sub ComboBox_SelectionChangeCommitted(Sender As ComboBox, e As EventArgs)
' '
' Look for other labels that have already been mapped to this target '
' '
If Me.OtherTargetCells.Any(Function(Cell) Cell.FormattedValue = Sender.Text) Then
If Me.IsInteractiveChange Then
MsgBox("Target [] is already mapped to Label []. If you want to map Target [] to Label [], you must first set Label [] to [Not mapped].", MsgBoxStyle.Exclamation, Me.DataGridView.FindForm.Text)
Me.IsInteractiveChange = False
Sender.SelectedIndex = 0
Me.IsInteractiveChange = True
End If
End If
End Sub
Private ReadOnly Property OtherTargets As List(Of String)
Get
Return Me.OtherTargetCells.Select(Function(Cell) DirectCast(Cell.FormattedValue, String)).ToList
End Get
End Property
Private ReadOnly Property CurrentTargetCell As DataGridViewCell
Get
Return Me.AllTargetCells(Me.DataGridView.CurrentRow.Index)
End Get
End Property
Private ReadOnly Property AllTargetCells As List(Of DataGridViewCell)
Get
Dim oAllCells As IEnumerable(Of DataGridViewCell)
Dim oRows As IEnumerable(Of DataGridViewRow)
oRows = Me.DataGridView.Rows.Cast(Of DataGridViewRow)
oAllCells = oRows.SelectMany(Function(Row) Row.Cells.Cast(Of DataGridViewCell))
Return oAllCells.Where(Function(Cell) TypeOf Cell Is DataGridViewComboBoxCell).ToList
End Get
End Property
Private ReadOnly Property OtherTargetCells As List(Of DataGridViewCell)
Get
Return Me.AllTargetCells.Where(Function(Cell) Cell.RowIndex <> Me.RowIndex).ToList
End Get
End Property
Private ReadOnly Property RowIndex As Integer
Get
Return Me.DataGridView.CurrentRow.Index
End Get
End Property
Private IsInteractiveChange As Boolean = True
Private ReadOnly ComboBoxes As New Dictionary(Of Integer, ComboBox)
End Class
End Namespace
Form1.vb
Public Class Form1
Inherits Form
Public Sub New()
Dim oColTargets As Mapping.TargetsColumn
Dim oTargets As IEnumerable(Of String)
Dim oQuery As Func(Of Target, Boolean)
Dim sChannel As String
Dim oTarget As Target
Dim oMaps As Dictionary(Of Integer, String)
Dim oMap As Map
Dim _
oColChannels,
oColLabels As DataGridViewTextBoxColumn
Me.InitializeComponent()
Me.Targets.Add(New Target("Not mapped"))
sChannel = String.Empty
oQuery = Function(Target) Target.Value = sChannel
'oTargets = Reader.Client.Create.Call(Function(Service As Reader.IService) Service.GetChannelTargets)'
oTargets = New List(Of String) From {"Scale", "SCC", "CO", "O2"}
oTargets.ToList.ForEach(Sub(Target)
Me.Targets.Add(New Target(Target))
End Sub)
'oMaps = Reader.Client.Create.Call(Function(Service As Reader.IService) Service.GetChannelMaps)'
oMaps = New Dictionary(Of Integer, String) From {{3, "Test"}, {7, "SCC"}, {8, "Scale"}, {9, "CO"}, {10, "O2"}}
oMaps.ToList.ForEach(Sub(Map)
sChannel = Map.Value
If Me.Targets.Any(oQuery) Then
oTarget = Me.Targets.Single(oQuery)
Else
oTarget = Me.Targets.First
End If
oMap = New Map With {
.Channel = Map.Key,
.Label = Map.Value,
.Target = oTarget
}
Me.Maps.Add(oMap)
End Sub)
oColChannels = New DataGridViewTextBoxColumn With {
.DataPropertyName = NameOf(Map.Channel),
.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader,
.HeaderText = NameOf(Map.Channel),
.ReadOnly = True,
.Name = NameOf(oColChannels)
}
oColLabels = New DataGridViewTextBoxColumn With {
.DataPropertyName = NameOf(Map.Label),
.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader,
.HeaderText = NameOf(Map.Label),
.ReadOnly = True,
.Name = NameOf(oColLabels)
}
oColTargets = New Mapping.TargetsColumn With {
.DataPropertyName = NameOf(Map.Target),
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
.DisplayMember = NameOf(Target.Value),
.ValueMember = NameOf(Target.Self),
.HeaderText = NameOf(Map.Target),
.DataSource = Me.Targets,
.Name = NameOf(oColTargets)
}
dgvMapping.AutoGenerateColumns = False
dgvMapping.Columns.AddRange({oColChannels, oColLabels, oColTargets})
For Each oColumn As DataGridViewColumn In dgvMapping.Columns
oColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
If oColumn.Index = 0 Then
oColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
End If
Next
dgvMapping.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
dgvMapping.DataSource = New BindingList(Of Map)(Me.Maps)
If dgvMapping.RowCount = 0 Then
dgvMapping.Height = 150
Else
dgvMapping.Height = ((dgvMapping.RowCount + 0) * dgvMapping.Rows(0).Height) + dgvMapping.ColumnHeadersHeight
End If
End Sub
Private Sub Form1_FormClosing(Sender As Form1, e As FormClosingEventArgs) Handles Me.FormClosing
Dim oPolicy As Target = Me.Maps.First.Target
Dim sName As String = Me.Maps.First.Channel
End Sub
Private Sub _dgvMapping_DataError(Sender As DataGridView, e As DataGridViewDataErrorEventArgs) Handles dgvMapping.DataError
MsgBox(e.Exception.Message, MsgBoxStyle.Critical, Me.Text)
End Sub
Private Targets As New BindingList(Of Target)
Private Maps As New List(Of Map)
End Class
Public Class Map
Public Property Channel As Integer
Public Property Label As String
Public Property Target As Target
End Class
Public Class Target
Public Sub New(Target As String)
Me.Value = Target
End Sub
Public ReadOnly Property Self As Target
Get
Return Me
End Get
End Property
Public ReadOnly Property Value As String
End Class
Form1.Designer.vb
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.'
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer'
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer'
'It can be modified using the Windows Form Designer.'
'Do not modify it using the code editor.'
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.dgvMapping = New System.Windows.Forms.DataGridView()
CType(Me.dgvMapping, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
' '
'dgvMapping'
' '
Me.dgvMapping.AllowUserToAddRows = False
Me.dgvMapping.AllowUserToDeleteRows = False
Me.dgvMapping.AllowUserToOrderColumns = True
Me.dgvMapping.AllowUserToResizeColumns = False
Me.dgvMapping.AllowUserToResizeRows = False
Me.dgvMapping.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dgvMapping.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter
Me.dgvMapping.Location = New System.Drawing.Point(12, 12)
Me.dgvMapping.Name = "dgvMapping"
Me.dgvMapping.RowHeadersVisible = False
Me.dgvMapping.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
Me.dgvMapping.Size = New System.Drawing.Size(250, 150)
Me.dgvMapping.TabIndex = 0
' '
'Form1'
' '
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.dgvMapping)
Me.Font = New System.Drawing.Font("Segoe UI", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Form1"
CType(Me.dgvMapping, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents dgvMapping As DataGridView
End Class
Fixed.
I was instantiating a new event handler object for each AddHandler/RemoveHandler call.
When I removed the instantiations and used simple expressions instead, the ComboBoxes started behaving correctly.
Public Sub New()
Task.Run(Sub()
While Me.DataGridView Is Nothing
End While
RemoveHandler Me.DataGridView.EditingControlShowing, AddressOf DataGridView_EditingControlShowing
AddHandler Me.DataGridView.EditingControlShowing, AddressOf DataGridView_EditingControlShowing
End Sub)
End Sub
Private Sub DataGridView_EditingControlShowing(Sender As Object, e As DataGridViewEditingControlShowingEventArgs)
Dim oComboBox As ComboBox
If TypeOf e.Control Is ComboBox Then
oComboBox = e.Control
oComboBox.DrawMode = DrawMode.OwnerDrawFixed
RemoveHandler oComboBox.DrawItem, AddressOf ComboBox_DrawItem
AddHandler oComboBox.DrawItem, AddressOf ComboBox_DrawItem
RemoveHandler oComboBox.SelectionChangeCommitted, AddressOf ComboBox_SelectionChangeCommitted
AddHandler oComboBox.SelectionChangeCommitted, AddressOf ComboBox_SelectionChangeCommitted
End If
End Sub
I had to relax the Sender parameter types to Object in the event handler methods, but that didn't carry any serious consequence.
Private Sub DataGridView_EditingControlShowing(Sender As Object, e As DataGridViewEditingControlShowingEventArgs)
End Sub
Private Sub ComboBox_DrawItem(Sender As Object, e As DrawItemEventArgs)
End Sub
Private Sub ComboBox_SelectionChangeCommitted(Sender As Object, e As EventArgs)
End Sub
For what it's worth: I generally prefer to constrain the Sender parameter to the calling type, for more efficient coding, but that wasn't possible in this case. Nevertheless, the only impact was the need to cast the Sender in one place in one method body:
Dim oQuery = Function(Cell) Cell.FormattedValue = DirectCast(Sender, ComboBox).Text
It works as expected now.
upon initialization of my UI i get the following very strange behavior regarding to the drawing of the datagridview:
Basically, expect the first row header and the column headers (which i did not include in the pic) it looks like the DGV prints what is on the Screen "behind" his application.
What the hell is this and does anyone know a way to fix it?
Code of Container:
Public Class DGVControl
Dim dt As DataTable
Public Sub init()
dt = New DataTable
Dim arr(ldfAttributes.Count - 1) As String
Dim cms As New ContextMenuStrip
Dim i As Integer = 0
For Each att As String In Attributes.Keys
Dim cmsitem As New ToolStripMenuItem
dt.Columns.Add(att, GetType(String))
cmsitem.Name = att
cmsitem.Text = att
cmsitem.Owner = cms
cmsitem.CheckOnClick = True
cmsitem.Checked = my.Settings.shownColumns.Contains(att)
AddHandler cmsitem.CheckedChanged, AddressOf showOrHideColumn
cms.Items.Add(cmsitem)
arr(i) = "No Data"
i += 1
Next
For i = 1 To my.settings.anzEntries
dt.Rows.Add(arr)
Next
MainDGV.DataSource = dt
MainDGV.ContextMenuStrip = cms
For Each attName as String In Attributes.key
showOrHideColumn(cms.Items(attName), New EventArgs())
Next
MainDGV.RowHeadersWidth = 90
MainDGV.RowTemplate.Height = 40
MainDGV.RowHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.RowHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.ColumnHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.ColumnHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.BackgroundColor = Color.White
End Sub
Private Sub showOrHideColumn(sender As Object, e As EventArgs)
Dim cmsitem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
MainDGV.Columns(cmsitem.Name).Visible = cmsitem.Checked
End Sub
'taken from: http://stackoverflow.com/questions/710064/adding-text-to-datagridview-row-header
Private Sub nameRowHeaders(sender As Object, e As EventArgs) Handles MainDGV.DataBindingComplete
Dim dgv As DataGridView = CType(sender, DataGridView)
For i As Integer = 0 To dgv.RowCount - 1
dgv.Rows(i).HeaderCell.Value = ("Entry " &(i+1).toString())
Next
End Sub
End Class
EDIT:
As soon as you once select a row, all cells will be displayed in the right way until you restart the application
I have a programs path..like utorrent and it pid too. I have achieved these values programatically using vb.net. I just want to hide their icon form tray just to run them in background and if possible attach the process with a hotkey to call them back. Is there any way to achieve this.
Option Strict On
Option Explicit On
Option Infer Off
Imports TrayHelper
Public Class Form1
Dim x1, y1 As Single
Friend WithEvents lv As New ListView With {.Parent = Me, .Dock = DockStyle.Fill}
Private il As New ImageList
Dim nxt As Integer
Friend WithEvents mnuContextMenu As New ContextMenu() 'Moved this to be declared as global
Dim mnuItemHide As New MenuItem()
Dim mnuItemExit As New MenuItem()
Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Controls.Add(lv)
lv.View = View.Details
il.ColorDepth = ColorDepth.Depth32Bit
lv.SmallImageList = il
lv.Columns.Add("Button Text", 300, HorizontalAlignment.Left)
lv.Columns.Add("PID", 50, HorizontalAlignment.Left)
lv.Columns.Add("Process Path", 600, HorizontalAlignment.Left)
'Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
For Each b As TrayButton In things
If b.Icon IsNot Nothing Then
il.Images.Add(b.TrayIndex.ToString, b.Icon)
Else
' When we can't find an icon, the listview will display this form's one.
' You could try to grab the icon from the process path I suppose.
il.Images.Add(b.TrayIndex.ToString, Me.Icon)
End If
Dim lvi As New ListViewItem(b.Text)
lvi.SubItems.Add(b.ProcessIdentifier.ToString)
lvi.SubItems.Add(b.ProcessPath)
lvi.ImageKey = b.TrayIndex.ToString
lv.Items.Add(lvi)
Next
lv.MultiSelect = False
'lv.ContextMenu = mnuContextMenu 'Don`t need to add if done this way
lv.FullRowSelect = True 'Added this but, you don`t need it if you don`t want it
mnuItemHide.Text = "&Hide"
mnuItemExit.Text = "&Exit"
mnuContextMenu.MenuItems.Add(mnuItemHide)
mnuContextMenu.MenuItems.Add(mnuItemExit)
AddHandler mnuItemHide.Click, AddressOf Me.menuItem1_Click
End Sub
Private Sub lv_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lv.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
If lv.GetItemAt(e.X, e.Y) IsNot Nothing Then
lv.GetItemAt(e.X, e.Y).Selected = True
mnuContextMenu.Show(lv, New Point(e.X, e.Y))
mnuItemExit.Visible = True
mnuItemHide.Visible = True
End If
End If
End Sub
Private Sub menuItem1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtValue as String
txtValue = lv.FocusedItem.SubItems(2).Text
Kill(txtValue)
Dim txtValue1 As String
txtValue1 = lv.FocusedItem.SubItems(0).Text
MessageBox.Show(txtValue1 + " has been hidden")
End Sub
End Class
this is my code
To hide your form -> form1.visible=false
To hide your form from taskbar -> form1.ShowinTaskbar=false
then go to the form1 keydown event and put this...
If e.Control And e.KeyCode = Keys.Q Then ' ---> activate with Ctrl-Q
form1.visible=true
End If
I have a program which has a datagridview with two combobox and two textbox. The first combobox contains OIDs and the other Combobox contains SNMP Operation (Get & GetNext).
Now I want to add another ComboBox beside my OID’s Combobox which contains description for the OIDs (like 1.3.6.1.2.1.1.1.0 for sysDescr and so on), and also the value of the New ComboBox(the one with description of OIDs) changes automatically as the user changes the OID in the first combobox. Is it possible? If yes then how?
Here is the code:
Imports System
Imports SnmpSharpNet
Public Class Form1
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataGridView1.Columns.Add("NameOne", "Column One")
DataGridView1.Columns.Add("NameTwo", "Column Two")
Dim dataGridRow As New DataGridViewRow()
Dim cells As DataGridViewCell() = New DataGridViewCell(1) {}
Dim txt1A As New DataGridViewTextBoxCell()
Dim txt1B As New DataGridViewTextBoxCell()
txt1A.Value = "Host"
txt1B.Value = "115.186.118.130"
dataGridRow.Cells.Add(txt1A)
txt1A.[ReadOnly] = True
dataGridRow.Cells.Add(txt1B)
dataGridRow.Height = 20
DataGridView1.Rows.Add(dataGridRow)
dataGridRow = New DataGridViewRow()
cells = New DataGridViewCell(1) {}
Dim txt2A As New DataGridViewTextBoxCell()
Dim cbo1 As New DataGridViewComboBoxCell()
cbo1.Items.Add("1.3.6.1.2.1.1.1.0")
cbo1.Items.Add("1.3.6.1.2.1.1.2.0")
cbo1.Items.Add("1.3.6.1.2.1.1.3.0")
cbo1.Items.Add("1.3.6.1.2.1.1.4.0")
cbo1.Items.Add("1.3.6.1.2.1.1.5.0")
cbo1.Value = cbo1.Items(0)
cbo1.[ReadOnly] = False
txt2A.Value = "OIDs"
dataGridRow.Cells.Add(txt2A)
txt2A.[ReadOnly] = True
dataGridRow.Cells.Add(cbo1)
dataGridRow.Height = 20
DataGridView1.Rows.Add(dataGridRow)
Dim requestOid() As String
requestOid = New String() {cbo1.Selected}
dataGridRow = New DataGridViewRow()
cells = New DataGridViewCell(1) {}
Dim txt3A As New DataGridViewTextBoxCell()
Dim cbo2 As New DataGridViewComboBoxCell()
cbo2.Items.Add("Get")
cbo2.Items.Add("GetNext")
cbo2.Value = cbo2.Items(0)
cbo2.[ReadOnly] = False
txt3A.Value = "SNMP Operation"
dataGridRow.Cells.Add(txt3A)
txt3A.[ReadOnly] = True
dataGridRow.Cells.Add(cbo2)
dataGridRow.Height = 20
DataGridView1.Rows.Add(dataGridRow)
dataGridRow = New DataGridViewRow()
cells = New DataGridViewCell(1) {}
Dim txt4A As New DataGridViewTextBoxCell()
Dim txt4B As New DataGridViewTextBoxCell()
txt4A.Value = "Community String"
txt4B.Value = "public"
dataGridRow.Cells.Add(txt4A)
dataGridRow.Cells.Add(txt4B)
dataGridRow.Height = 20
DataGridView1.Rows.Add(dataGridRow)
End Sub
Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
Dim comboControl As DataGridViewComboBoxEditingControl = TryCast(e.Control, DataGridViewComboBoxEditingControl)
If comboControl IsNot Nothing Then
' Set the DropDown style to get an editable ComboBox
If comboControl.DropDownStyle <> ComboBoxStyle.DropDown Then
comboControl.DropDownStyle = ComboBoxStyle.DropDown
End If
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim result As Dictionary(Of Oid, AsnType)
Dim cbo1 As New DataGridViewComboBoxCell()
Dim txt1B As New DataGridViewTextBoxCell()
txt1B.Value = "203.81.211.117"
Dim host As String
Dim community As String
host = DataGridView1.Rows(0).Cells(1).Value.ToString
community = DataGridView1.Rows(3).Cells(1).Value.ToString
Dim txt4B As New DataGridViewTextBoxCell()
txt4B.Value = "public"
Dim snmp As New SimpleSnmp
snmp = New SimpleSnmp(DataGridView1.Rows(0).Cells(1).Value.ToString, DataGridView1.Rows(3).Cells(1).Value.ToString)
'abc.Text = txtsnmpaction.SelectedItem
result = snmp.Get(SnmpVersion.Ver1, New String() {DataGridView1.Rows(1).Cells(1).Value.ToString()})
'result = snmp.GetNext(SnmpVersion.Ver1, requestoid)
'If (txtsnmpaction = "GetBulk")
'result = snmp.GetBulk(New String() {".1.3.6.1.2", ".1.3.6.1.3"})
' End If
If Not snmp.Valid Then
MessageBox.Show("Invalid hostname/community")
End If
If result IsNot Nothing Then
Dim kvp As KeyValuePair(Of Oid, AsnType)
For Each kvp In result
MessageBox.Show(kvp.Key.ToString)
MessageBox.Show(SnmpConstants.GetTypeName(kvp.Value.Type))
MessageBox.Show(kvp.Value.ToString())
Next kvp
Else
MessageBox.Show("No results received")
End If
End Sub
End Class
I'd make the SNMP Operation a read-only text field and set it programatically. Handle the DataGridView1.CellValueChanged event.
EDIT: Changing description rather than SNMP operation.
Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
If e.ColumnIndex = 3 Then
Dim Row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
Dim Description As String = Nothing
Select Case Row.Cells(3).Value
Case "1.3.6.1.2.1.1.1.0" : Description = "sysDescr"
...
End Select
Row.Cells(5).Value = Description ' Change (5) to description column index.
End If
End Sub