How can I read the SelectedItem of a Listbox? - vb.net

I am trying to get the selected text in a ListBox to show in a list box.
I have a button that when I click, will show the text of a Selected item in a ListBox.
I've already tried getting the list box to show the text in a textbox using Listbox.SelectedItem:
Listbox1.SelectedItem = Textbox1.Text
When I do this, I get the error:
System.NullReferenceException: 'Object variable or With block variable
not set.'

Your description is somewhat upside-down.
It's not clear whether you want to set a ListBox.SelectedItem using the Text of a TextBox or you want to set a TextBox.Text with the text of the SelectedItem of a ListBox.
The code says one thing, the description another. The error you have is probably caused by a null SelectedItem (you haven't selected anything).
But, if you want to set a TextBox.Text with the ListBox.SelectedItem text, you can use the GetItemText() method. This method has a plus, it won't raise an exception if the Listbox has no selected Items (the SelectedItem is null (nothing)).
TextBox1.Text = ListBox1.GetItemText(ListBox1.SelectedItem)
The opposite:
You can use the ListBox FindString() and FindStringExact() methods to locate an item in the control's collection corresponding to a given string.
The former finds the first items in the ListBox that starts with the specified string, the latter matches only the whole string.
The search can begin from a specific index. It's not case sensitive.
listBox1.SelectedIndex = listBox1.FindString(textBox1.Text, 0)
' or
listBox1.SelectedIndex = listBox1.FindStringExact(textBox1.Text, 0)
You can continue the search specifying, as the starting point, the index of the item previously found:
private int lboxSearchIndex = -1;
Private Sub ButtonSearch_Click(sender As Object, e As EventArgs) Handles ButtonSearch.Click
lboxSearchIndex = listBox1.FindString(textBox1.Text, lboxSearchIndex)
listBox1.SelectedIndex = lboxSearchIndex
End Sub
Setting the SelectedItem is like using the FindStringExact() method.
Only a full match will set the item, but it's case sensitive.

Listbox1.Text=textbox1.text
Let me know its help you

Related

For a combobox, selectedIndex returns 0 while selectedtext returns a value

Once I select a value from a Combobox and save the form, ComboBox.SelectedText contains the value selected but ComboBox.SelectedIndex is returning 0 always for each item in the list. Below is just a sample code for reference.
If (combobox1.SelectedIndex = 0 Or combobox1.SelectedText = "")
MessageBox.Show("No value selected")
else
MessageBox.Show("Some value selected")
End If
Some code to illustrate usage
Private Sub ComboBox1_SelectedIndexChanged(sender As Object,
e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'check for no item selected
If ComboBox1.SelectedIndex < 0 Then
Stop 'no item
Else
Dim idx As Integer = ComboBox1.SelectedIndex
Dim val As String = CStr(ComboBox1.SelectedItem) '<-- use SelectedItem
Stop
End If
End Sub
Small Answer
SelectedText is not the same as SelectedItem. Take a look at ComboBox.SelectedText:
Gets or sets the text that is selected in the editable portion of a ComboBox.
I think that you are confusing this with ComboBox.SelectedItem
SelectedIndex: -1 if nothing selected, otherwise the index of the selected item
SelectedValue: null if nothing selected, otherwise the selected item
SelectedText: the text that the operator marked in the editable part of the combo box.
** Room for improvement **
You use VB. My VB is a bit rusty, so I'll give my answer in C#. I guess you'll get the gist.
In Winforms, whenever you want to fill a that shows a sequence of items, like ComboBoxes, ListBoxes, DataGridViews, Charts, etc, there are usually two methods:
Fill the ComboBox one by one with the texts that you want to display
Use a DataSource: fill it with the Items that you want to be selectable, and tell the ComboBox which property of the selectable items you want to display.
Use the first method if you only want to display a constant array of strings. Fill ComboBox.Items. When an item is selected, use SelectedIndex to get the index of the selected string. Use ComboBox.Items[selectedIndex] to get the selected string.
If the string represents something more than just a string, for instance the text represents a Customer, or a Product. It is usually easier to use the DataSource method.
To do that, you use property ComboBox.DataSource to tell the ComboBox which Customersit should display. In ComboBox.ValueMember you tell the ComboBox which Customer poperty should be used to represent the Customer, for instance the name of the Customer.
Once the operator selected the name of the Customer, you get the complete Selected Customer using property ComboBox.SelectedItem:
List<Customer> availableCustomers = ...
ComboBox combo1 = new ComboBox(...);
combo1.ValueMember = nameof(Customer.Name); // the Customer property that you want to display
combo1.DataSource = availableCustomers;
After the operator selected an item, you can process the event, and fetch the selected customer immediately:
Customer selectedCustomer = (Customer)cmbo1.SelectedValue;
ProcessSelectedCustomer(selectedCustomer);
Of course you should only select a property that is unique. If you have two Customers named "Hans Brinker", operators wouldn't know which name represents which Customer.
Apart from the nice thing that you don't have to do a lookup from SelectedIndex to what this selected item represents (a Customer), you are independent of the order in which the Customers are displayed.
Another nice thing: if in future versions you want to change from ComboBox to ListBox, or maybe even to DataGridView, you won't have to change your model drastically: the control still shows a sequence of Customers, and once an operator selects something that represents this Customer (Name? Id?, DataGridView Row?), you get the complete Customer.
(1)ComboBox1.SelectedIndex starts from -1, when you are not selected, ComboBox1.SelectedIndex=-1
(2)When you click combobox1.items, SelectedText is always "".
This is because, at the time of these events(SelectedIndexChanged, SelectedValueChanged.. ), the previous SelectedText value has been cleared and the new value has not yet been set. You can use the SelectedItem property instead.
E.g:combobox1.SelectedItem
Please try the following code.
If ComboBox1.SelectedIndex = -1 Then
MessageBox.Show("No value selected")
Else
MessageBox.Show("Some value selected")
End If

Odd behaviour when trying to de-selecting text in Combobox with SuggestAppend

I've got a DropDown combobox which is bound to a list. I am using SuggestAppend autocomplete based on the items from that list.
Once the item is selected from the suggest popup, the text is completed in the combobox as expected. However, the text stays selected and I am struggling to deselect it with an event. I can see a similar post (Deselect combobox text on leaving using suggestappend) , however the solution doesn't seem to apply in my case.
My combobox code:
Private Sub CboIFAfirm_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CboIFAfirm.SelectedIndexChanged
If CboIFAfirm.SelectedIndex > -1 Then
CboAdviser.SelectedIndex = -1
With CboIFAfirm
.SelectionStart = 0
.SelectionLength = 0
End With
CboAdviser.Select()
End If
End Sub
I have also tried setting the autocomplete mode to None before selecting the next Combobox without luck.
Interestingly, when text is selected the selectionlength shows 0 so it sorts of doesn't see it...
EDIT:
Another approach has failed too - I have added SendKeys.Send("{End}") at the bottom of my SelectedIndexChanged event but it only seems to work without selecting CboAdviser!?

How do i hide a control in a report based on a field value

I have a checkbox control that i need to hide if a Boolean value is false. I have tried using the Detail_Format event to no avail. i put the field value into another checkbox, then tried setting the visible property from the value in the checkbox, no dice. In the image below, the rightmost checkbox is showing the value of the field that determines if the checkbox to the left of it should be shown. I have the following code
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
If Me.chkRequireverify = True Then
Me.chkVerified.Visible = True
Else
Me.chkVerified.Visible = False
End If
'Me.chkVerified.Visible = Me.chkRequireverify
End Sub
when i tried using the Detail_Paint event, it errored out telling me that i cant change the visible property in this event.
Your code looks to be correct and could be shortened to simply:
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
Me.chkVerified.Visible = Me.chkRequireverify
End Sub
However, I believe the event handler for the OnFormat event will only be evaluated when viewing the report in Print Preview view, rather than in Report view.
Whilst the OnPaint event fires in Report view, you cannot modify certain properties after the report has been formatted, the Visible property being one such property, along with the Height & Width properties (and so you also cannot shrink the checkboxes to zero size).
It's been a while since I've used Access and VBA, but I believe what you're missing is .Value after the checkbox name in the if clause.
Try this : If Me.chkRequireverify.Value = True

How can be find selected index value of listBox

I have loaded datatable to listview.Now when i try to do a selected index and retrieve data to display in respective text box. I find some error "input string format incorrect".
but when i directly load from folder it works fine.
When i try to trace the error ---
Data that retrieved from Datatable.Im not able to find the index of the row.
But from folder and listed in ListView.Index value is found.
So far:
Dim breakfast As ListView.SelectedListViewItemCollection = Me.LOV.SelectedItems
For Each item1 In breakfast
index += Double.Parse(item1.SubItems(1).Text)
Next
"Input string format incorrect" means that the Double.Parse() Method throws an exception: The given string (item1.SubItems(1).Text) is not a valid number and cannot be casted into a double.
Use Double.TryParse to avoid an exception here.
From this post it seems below will be your answer
Private Sub listView_ItemCreated(sender As Object, e As ListViewItemEventArgs)
' exit if we have already selected an item; This is mainly helpful for
' postbacks, and will also serve to stop processing once we've found our
' key; Optionally we could remove the ItemCreated event from the ListView
' here instead of just returning.
If listView.SelectedIndex > -1 Then
Return
End If
Dim item As ListViewDataItem = TryCast(e.Item, ListViewDataItem)
' check to see if the item is the one we want to select (arbitrary) just return true if you want it selected
If DoSelectDataItem(item) = True Then
' setting the SelectedIndex is all we really need to do unless
' we want to change the template the item will use to render;
listView.SelectedIndex = item.DisplayIndex
If listView.SelectedItemTemplate IsNot Nothing Then
' Unfortunately ListView has already a selected a template to use;
' so clear that out
e.Item.Controls.Clear()
' intantiate the SelectedItemTemplate in our item;
' ListView will DataBind it for us later after ItemCreated has finished!
listView.SelectedItemTemplate.InstantiateIn(e.Item)
End If
End If
End Sub
Private Function DoSelectDataItem(item As ListViewDataItem) As Boolean
Return item.DisplayIndex = 0
' selects the first item in the list (this is just an example after all; keeping it simple :D )
End Function

How do I set a VB.Net ComboBox default value

I can not locate the correct method to make the first item in a combo box visible.
The app starts with an empty combo box. The user makes a radio box selection then clicks Go! (how original). The combo box is loaded via an LDAP query. All this is working just fine. The problem is the combo box still appears to the user to be empty. They must click the arrow to see the options.
How do I make the first option 'visible' after the users clicks Go!?
' Your code filling the combobox '
...
If myComboBox.Items.Count > 0 Then
myComboBox.SelectedIndex = 0 ' The first item has index 0 '
End If
Just go to the combo box properties - DropDownStyle and change it to "DropDownList"
This will make visible the first item.
OR
you can write this down in your program
Private Sub ComboBoxExp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load
AlarmHourSelect.Text = "YOUR DEFAULT VALUE"
AlarmMinuteSelect.Text = "YOUR DEFAULT VALUE"
End Sub
so when you start your program, the first thing it would do is set it on your assigned default value and later you can easily select your required option from the drop down list.
also keeping the DropDownStyle to DropDownList would make it look more cooler.
-Starkternate
because you have set index is 0 it shows always 1st value from combobox as input.
Try this :
With Me.ComboBox1
.DropDownStyle = ComboBoxStyle.DropDown
.Text = " "
End With
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
If ComboBox1.SelectedIndex = -1 Then
ComboBox1.SelectedIndex = 0
End If
Much simpler solution, Select the Combo-box, and in the option of Selected item, select the item index (0 for the first item) and set it to be the default value in the combo box.
Another good method for setting a DropDownList style combobox:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")