How to enable a button when an item is selected in a listBox
I'm stuck on a part of my assignment and wondering if someone could point me in the right direction.
Here's my problem, I have set my listBox button_up to disabled, but I need it to enable when there is at least 1 selected item in the listBox, here's my code for the remove button:
VB Code:
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If listBox.SelectedItems ' need selectedItem to = something??? Then
Me.btnRemove.Enabled = True
End If
Dim item As String = listBox.SelectedItem
Dim index As Integer = listBox.SelectedIndex
listBox.Items.RemoveAt(index)
listBox.Items.Insert(index - 1, item)
listBox.SelectedIndex = index - 1
end sub
Thanks for any help.
Re: How to enable a button when an item is selected in a listBox
If nothing is selected, the SelectedIndex property of the listbox is -1.
VB Code:
If ListBox1.SelectedIndex <> -1 Then
Btn.Enabled = True
End If
Re: How to enable a button when an item is selected in a listBox
Thanks for the quick response, bur the code you gave doesn't enable the button??
Re: How to enable a button when an item is selected in a listBox
You have to replace "Btn" with the name of your correct button. Do you want to enable button_up or btnRemove from inside btnRemove_click (the latter seems kind of impossible).
Re: How to enable a button when an item is selected in a listBox
sorry about the mistake, I want to enable button_up, here's my code again:
VB Code:
Private Sub btnUp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUp.Click
Dim item As String = listBox.SelectedItem
Dim index As Integer = listBox.SelectedIndex
listBox.Items.RemoveAt(index)
listBox.Items.Insert(index - 1, item)
listBox.SelectedIndex = index - 1
If listBox.SelectedIndex <> -1 Then
Me.btnUp.Enabled = True
End If
It still doesn't work?
Re: How to enable a button when an item is selected in a listBox
This approach is bound to throw exceptions but you fill face them as you go on(and learn to avoid them). The reason it is not working is because you are enabling the button if some condition is met when the very same button is clicked. How can you enable a button if it has to be clicked first in order to be enabled?
Put the code from your last post in the click event of some other button. I think in your design it should be the btnRemove's click event.
Re: How to enable a button when an item is selected in a listBox
Yeah, that does sound a lot better, will give it a try, thanks for your help half.