Vb.net - Only show context menu strip if item is clicked - vb.net

I've got a listview full of items. And I've added a contextmenustrip to that listview. Now, I want the menustrip to only appear if an item in the listview is selected. How can I do this?

The ContextMenuStrip class has the event Opening that could be handled to check the presence or not of selected items on the ListView.
This event receives an CancelEventArgs parameter where you can find the Cancel property and set it to True to cancel the opening if the condition required happens.
Private Sub ContextMenuStrip1_Opening(sender As System.Object, e As CancelEventArgs) _
Handles ContextMenuStrip1.Opening
If Me.listView1.SelectedItems.Count = 0 Then
e.Cancel = True
End If
End Sub

Related

Set focus on ListView

I've just starting using ListView control in VS2019.
I'm sure there's a simple solution, but I can't figure out how to set the focus on the control like I can with most other controls.
I want the ListView to be focused when the form loads, and then I want to programmatically focus an item in the ListView.
I know how to focus a particular item using ListView1.FocusedItem.Index, but I can't focus the actual control.
I have tried both ListView1.Select() and ListView1.Focus() but these seem to do nothing.
What am I missing!?
Thanks
EDIT
As pointed out below, the control is actually focused using ListView1.Select() it's just not focused in the same way I'd expect, for example, a ListBox to be focused - ie, with a particular item in the list highlighted.
How would you best focus the ListView and highlight a particular item?
I have tried this in a command button on the form, but it doesn't do anything. Though it works correctly AFTER I click an Item in the ListView.
ListView1.Select()
If (ListView1.SelectedItems.Count > 0) Then
ListView1.Items(4).Selected = True
End If
listview1.focus()
For I as Integer = 0 to ListView1.Items.Count - 1
If ListView1.Items(i).Text = "youritemtexthere" then
ListView1.Items(i).Selected = true
End If
End For
or if you have the index but not a known text just do:
listview1.focus()
ListView1.Items(index).Selected = true
ListView1.Select works, you probably just don't see that the ListView has focus. You can verify this by checking the GotFocus and LostFocus events on the ListView:
Private Sub ListView1_GotFocus(sender As Object, e As EventArgs) Handles ListView1.GotFocus
Me.Text = "Got Focus"
End Sub
Private Sub ListView1_LostFocus(sender As Object, e As EventArgs) Handles ListView1.LostFocus
Me.Text = "Lost Focus"
End Sub
This simply updates your Form's title to "Got Focus" or "Lost Focus". You can force the focus in your Form Load event:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.Items.Add("a")
ListView1.Items.Add("b")
ListView1.Items.Add("c")
ListView1.Select()
End Sub

How do I set the tabIndex for a Button at run time in WinForms?

I have a generic message box where we have a few panels in which we add controls at runtime.
Here in my form, I've already pnlBottom on which pnlButtons is there along with some other controls.
Now at run time I'm adding an OK button to pnlButtons which is there on pnlBottom. I'm not setting a TabIndex for any controls in the Designer.vb file.
I'm trying to keep the focus on the OK button using the code below, but it's not working.
For Each control As Control In Me.Controls
If TypeOf (control) Is Panel Then
Dim pnlBottons As Panel = CType(control, Panel)
If pnlBottons.Name = "pnlBottom" Then
For Each ctrl As Control In control.Controls
Dim pnlButtons As Panel = CType(ctrl, Panel)
If pnlButtons.Name = "pnlButtons" Then
For Each ctrlbtn As Control In ctrl.Controls
If TypeOf (ctrlbtn) Is Button Then
Dim textBox As Button = CType(ctrlbtn, Button)
textBox.Parent.Parent.TabIndex = 0
textBox.Parent.TabIndex = 0
textBox.TabIndex = 0
End If
Next
End If
Next
End If
End If
Next
Here I'm setting the TabIndex for pnlBottom, pnlButtons and OK button as 0.
Please suggest how to focus the OK button.
You can set the focus on a control during Form Load event using either of the following options. (Ref: How to set the focus on a control when the form loads in Visual Basic .NET or in Visual Basic 2005. The original link is broken, so use Wayback Machine.)
1- Control.Select Method
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.OKButton.Select()
End Sub
Focus is a low-level method intended primarily for custom control
authors. Instead, application programmers should use the Select method
or the ActiveControl property for child controls, or the Activate
method for forms.
2- Form.ActiveControl Property
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.ActiveControl = Me.OKButton
End Sub
3- Control.Focus Method
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.Show()
Me.OKButton.Focus()
End Sub
The reason that we call Me.Show() is to set forms visible to true. according to:
You can use the Control.Focus method in the Load event of the form to
set the focus on a control only after the Visible property of the form
is set to True.
In cases you can not use Me.OKButton you can find the control you want like this:
Dim control = Me.Controls.Find("OKButton", True).FirstOrDefault()
If Not control Is Nothing Then
control.Select() 'or other stuff
End If

Are ListviewItems ever truely deselected?

I have a listview with several items in it. If I have an item selected and click in an empty white space or anywhere else on the form the highlight is removed but .FocusedItem & .SelectedItems still report an item is selected.
I have events that I want to trigger when no listviewitems are selected, but that never seems to occur. How do I detect if no items are selected or does that ever actually happen after that first item gets clicked?
Private Sub lstCats_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCats.SelectedIndexChanged
If IsNothing(lstCats.FocusedItem) Then
DisableGUI()
Else
EnableGUI()
DisplayQuestions()
End If
End Sub
Basically DisableGUI() will never execute.
Thanks!
You can deselect all items in the ListView by clicking on an empty part of the ListView control (that is not on one of the items). For example:
Private Sub lstCats_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCats.SelectedIndexChanged
If lstCats.SelectedItems.Count = 0 Then
DisableGUI()
Else
EnableGUI()
DisplayQuestions()
End If
End Sub
Note if you click on an item in the ListView, SelectedItems will be > 0. If you click on the background of the ListView (not on an item), SelectedItems will be = 0. This assumes that there is part of the ListView control that does not contain an item.

How can I find the sender of ContextMenuStrip?

Situation:
I have a context menu in a VB.NET form with fires an event handler on ItemClicked. The auto-generated subroutine receives sender and e as parameters. As I don't reinvent the wheel multiple times, I linked this context menu to three text boxes. Let's name them Textbox1, Textbox2 and Textbox3.
Problem: How can I figure out in which textbox the menu was opened?
Okay, what did I already try?
sender contains the menu itself,
e.ClickedItem just returns the single menu item that was selected.
sender.Parent is always nothing
sender.OwnerItem is also always Nothing`
Me.Textbox1.Focused is always False, even if its the "parent" control of the menu.
Okay, I found a solution that works fine, and here's the code for all VB.NET coders that have the same problem.
The context menu is linked in TextBox1, so we need to add another event handler that saves the sending control into the menu:
Private Sub TextBox1_MouseUp(sender As Windows.Forms.Control, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp
If e.Button = Windows.Forms.MouseButtons.Right Then
ContextMenu.Tag = sender
End If
End Sub
And this is the code of the event handler when clicking a menu item:
Private Sub ContextMenu_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenu.ItemClicked
ContextMenu.Close()
If ContextMenu.Tag Is Nothing Then
Debug.Print("debug info: forgot to set sender? well ... KABOOM!")
Exit Sub
End If
Dim oParent As Windows.Forms.Control
Try
oParent = ContextMenu.Tag
Catch ex As Exception
Debug.Print("debug info: tag contains data other than sender control. well ... KABOOM!")
Exit Sub
End Try
' Do fancy stuff here.
' Release sender
ContextMenu.Tag = Nothing
End Sub
The ContextMenuStrip has a SourceControl property which contains a reference to the control which opened the menu. The event fires from one of the ToolStripMenuItems in the ContextMenuStrip, so you have to get the "parent" first:
' cast sender to menuitem
Dim mi = CType(sender, ToolStripMenuItem)
' cast mi.Owner to CMS
Dim cms = CType(mi.Owner, ContextMenuStrip)
' the control which opened the menu:
Console.WriteLine(cms.SourceControl.Name)
Under certain conditions the SourceControl can get lost but you can track it yourself with a variable and the parent ContextMenuStrip Opening event:
' tracking var:
Private MenuSourceControl As Control
Private Sub cms_Opening(sender As Object, e As CancelEventArgs) Handles cms.Opening
' set reference in case/before it is lost
MenuSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub CutToolStripMenuItem_Click(sender...
If MenuSourceControl IsNot Nothing Then
' do your stuff
' optionally clear the tracking var
MenuSourceControl = Nothing
End If
End Sub
It should be also easier to get the SourceControl when dealing with sub items
You can also capture the related control in the MouseDown event of the related Control in cases where the same menu is used with different controls:
Private Sub lv2_MouseDown(sender As Object,
e As MouseEventArgs) Handles lv2.MouseDown,
myLV.MouseDown, lv1.MouseDown ...
If e.Button = Windows.Forms.MouseButtons.Right Then
MenuSourceControl = DirectCast(sender, Control)
End If
End Sub

Can't set focus on a Windows Forms textbox

I can't seem to get input focus on a textbox when a tab page first comes up (I'm using Windows Forms, VB.NET 3.5).
I have a textbox on a panel on a tab page, and I want the focus to be on the textbox when the tab page comes up. I want the user to be able to start typing immediately in the focused textbox without having to click on the textbox. I have tab stops set in the order I want and the textbox is the first tab stop. The tab stops work except that when the tab page comes up the focus is not on the textbox, i.e. the one that's first in the tab order.
In the Enter event handler of the tab page I call the Focus method of the text box, but it returns False and does nothing, no error messages. I know I can access the text box because
at the same point in the code I can set the text of the text box.
If it matters, the layout of the tab page is a little complicated:
frmFoo/TabControl1/TabPageX/Panel1/Panel2/TextBox1
I want to set the focus on TextBox1.
What's the best way to get the focus on the desired textbox?
If setting focus is the best way, why is the textbox.Focus() method failing?
I would assume you are attempting to set focus in the form load event handler? If so, you need to do a Me.Show() to actually create the onscreen controls before focus can be set. Something along the lines of:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Show()
Application.DoEvents()
TextBox1.Focus()
End Sub
If you don't do the Me.Show(), the form is NOT displayed until the load event is complete.
For the tab control, handle the _SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then
TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
TextBox4.Focus()
End If
You will still want to set the initial focus in the load event as shown above if the first field selected is to be the textbox on the tab control.
Try either:
Me.ActiveControl = TextBox1
or
TextBox1.Select()
Do the control.Focus() in the OnShown event. You don't need any of the DoEvents logic which didn't work for me anyway.
You Should Use Selected Event of TabControl
Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
If e.TabPage.Name = "TabPage1" Then
TextBox1.Select()
End If
End Sub
As I have Checked in Both TabControl.Selected and TabPage.Enter Event can set Select TextBox. I think there is some other elements stealing focus. please varify
Any of the solutions I found online don't solve the problem when the control is on a tab page.
However, this works:
(1) set the TabIndex of the control to 0.
(2) In your code that handles the tabpage event, do the following:
SendKeys.Send("{TAB}")
If SendKeys doesn't seem to be a valid statment, make sure you have the following import at the top of your code file:
Imports System.Windows.Forms
I found that the TabControl gets the focus when the Selected event completes. To make this work I used the Paint event of the TabPage to set the focus of the desired object.
Private Sub TabChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tab1.Paint, Tab2.Paint, Tab3.Paint
Select Case sender.Name
Case "Tab1"
Textbox1.Focus()
Case "Tab2"
T3extbox2.Focus()
Case "Tab3"
Textbox3.Focus()
End Select
End Sub
Try the Activated event of the form like this:
Private Sub Form2_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
'SendKeys.Send("{TAB}") this line works too
TextBox1.Focus()
End Sub
That is guaranteed to work.
I once had the same problem but i solved it using the Me.activate() function.