Show decimal type in listbox VB2008 - vb.net

I have problem in my project with VB 2008.
I have 5 textbox that only contains numeric. From all of inputted value will be shown in Listbox and sort by ascending.
I use this code below
Private Sub InptBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InptBtn.Click
Dim List As New List(Of Double)
Dim chkList As New Integer
Dim getData() As String = {Inpt1.Text, Inpt2.Text, Inpt3.Text, Inpt4.Text, Inpt5.Text, Inpt6.Text}
' empty check
For idx As Integer = 0 To getData.Length - 1
chkList += getData(idx).Trim.Length
Next
If chkList = 0 Then
MessageBox.Show("EMPTY!", "WARNING!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' numeric check
Dim d1 As Double = 0
For idx As Integer = 0 To getData.Length - 1
If Double.TryParse(getData(idx), d1) Then
List.Add(d1)
End If
Next
If List.Count = 0 Then
MessageBox.Show("Please fill with number!", "WARNING!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
List.Sort()
ListBox.DataSource = List
End Sub
It's work! But I have 1 problem.
If I try to input
0.0000000000001 or 0.00000000000000000002
It's shown like
1E-13 or 2E-20
I tried to use ToString method and change List type by String after sorting like code below, but it doesn't work.
For idx As Integer = 0 To getData.Length - 1
If Double.TryParse(getData(idx), d1) Then
List.Add(d1.ToString())
End If
Next
Could I show all inputted value as I inputted with Decimal type? Or there's some way to shown it with other type?
Shown like below in Listbox:
0.0000000000001 or 0.00000000000000000002
Thank you so much!

Can you try this ?
For idx As Integer = 0 To getData.Length - 1
If Double.TryParse(getData(idx), d1) Then
List.Add(FormatNumber(d1.ToString, 20))
End If
Next

Related

getting System.InvalidOperationException: Listbox DataSource VB.net

This is the error I am getting
System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'
I have a Listbox that is databound The list of items are stored days table the saved value is stored in a record table. The List is a Comma Separated List E.G: 1,2,3,4,5
Would equate to Items with values of 1 -5 being selected on load.
This is the save Routine which Works perfectly
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.Leave
Dim listboxItems As New List(Of String)
For Each row As DataRowView In ListBox1.SelectedItems
listboxItems.Add(row("IDNum"))
Next row
selectLoad = True
lblDays.Text = String.Join(",", listboxItems.ToArray())
End Sub
This is Routine Which is Throwing the error.
Private Sub BGWLoadData_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWLoadData.RunWorkerCompleted
Dim TextBoxStrings() As String = {""}
Try
Dim TempStr() As String = lblDays.Text.Split(",")
ReDim TextBoxStrings(TempStr.Count - 1)
TextBoxStrings = TempStr
Catch ex As Exception
End Try
Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
For a As Integer = 0 To TextBoxStrings.Count - 1
Try
TextBoxDoubles(a) = TextBoxStrings(a)
Catch ex As Exception
TextBoxDoubles(a) = 0
End Try
Next
Do While DaysBound = False
Application.DoEvents()
Loop
ListBox1.SelectedItems.Clear()
Dim TempIndex As Integer = 0
For Each row As DataRowView In ListBox1.Items
For a As Integer = 0 To TextBoxDoubles.Count - 1
If row("IDNum") = TextBoxDoubles(a) Then
ListBox1.SetSelected(TempIndex, True)
End If
Next
TempIndex = TempIndex + 1
Next row
End Sub
What am I doing wrong or what can be done to make the code more efficient.
Edit:
Error Occurs at Next Row.
Also telling me I have done something wrong isn't helpful I know something is Wrong because I am getting errors. I am asking for is how to fix this with a code snippet or something.
This Has been Solved by Adding a second arrary
If selectLoad = False Then
' convert CSV of IDNums of selected items in listbox into string array
Dim TextBoxStrings() As String = {""}
Try
Dim TempStr() As String = lblDays.Text.Split(",")
ReDim TextBoxStrings(TempStr.Count - 1)
TextBoxStrings = TempStr
Catch ex As Exception
End Try
' convert string array to double array
Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
For a As Integer = 0 To TextBoxStrings.Count - 1
Try
TextBoxDoubles(a) = TextBoxStrings(a)
Catch ex As Exception
TextBoxDoubles(a) = -1
End Try
Next
' load underlying IDNums into temporary array
Dim TempIndex As Integer = 0
Dim TempIDNums(ListBox1.Items.Count - 1) As Integer
For Each row As DataRowView In ListBox1.Items
TempIDNums(TempIndex) = row("IDNum")
TempIndex = TempIndex + 1
Next row
' if any of the underlying IDNums are found in the CSV, select that item in the listbox
ListBox1.SelectedItems.Clear()
For ListItemCounter As Integer = 0 To TempIDNums.Count - 1
For SelectedItemCounter As Integer = 0 To TextBoxDoubles.Count - 1
If TempIDNums(ListItemCounter) = TextBoxDoubles(SelectedItemCounter) Then
ListBox1.SetSelected(ListItemCounter, True)
End If
Next
Next
End If

how to check checklistbox items using datagridview vb.net?

I'm just a beginner for coding and I want to programmatically check items in checklistbox using datagridview.
Data grid view values are seperated with commas like this jhon,Metilda,saman,.
Checklistbox name as chklistinput and please help me to solve this ?
'Full coding is here..............................
Private Sub TextBox10_TextChanged(sender As Object, e As EventArgs) Handles TextBox10.TextChanged
'this is ok and searching as I want
Dim SearchV As String = TextBox10.Text
SearchV = "%" + TextBox10.Text + "%"
Me.PassIssuingRecordTableAdapter.FillBy(Me.Database4DataSet.PassIssuingRecord, SearchV)
'But the problem bigins here
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
For Each x In areasback1
For i = 0 To areasback.Count - 1
If chklistInput.Items(i).ToString() = x.ToString() Then
chklistInput.SetItemChecked(i, False)
End If
Next
Next
End Sub
You have to loop over chklistInput.Items.Count - 1 instead of areasback.Count - 1
use the following code:
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
Dim intCount as integer = 0
For each str as string in areasback1
For intCount = 0 To chklistInput.Items.Count - 1
If chklistInput.Items(intCount).ToString() = str Then
chklistInput.SetItemChecked(intCount , True)
End If
Next
Next
chklistInput.Refresh()
Note: comparing is case sensitive

How to search in listview

I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
I don't understand your code, but I do understand the question. Below is example code to search all rows and columns of a listview. Search is case insensitive and supports a "find next match" scenario. If a match or partial match is found in any column the row is selected. TextBox1 gets the text to find. FindBtn starts a new search.
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
Instead of looping like that through the ListView, try using a For Each instead:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
This will select every item which has a text match in a subitem.
Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.
This is the easiest way to search in listview and combobox controls in vb net
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if

Index out-of-range error

I am getting an error when I execute this button event: here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Try
' get the details of the item
Dim R As Your_pharmacy.POSDS.ItemsRow = Button1.Tag
' next search for the barcode in the datagridview
Dim I As Integer
Dim ItemLoc As Integer = -1
For I = 0 To DGV1.Rows.Count - 1
If R.barcodeNumber = DGV1.Rows(I).Cells(0).Value Then
' item found
ItemLoc = I
Exit For
End If
Next
' if item is not found, add it
If ItemLoc = -1 Then
DGV1.Rows.Add(R.barcodeNumber, R.ItemName, R.BuyPrice, R.SellPrice, 1, R.SellPrice)
Else
' if item is already there increase its count
Dim ItemCount As Long = DGV1.Rows(ItemLoc).Cells(4).Value
ItemCount += 1
Dim NewPrice As Decimal = R.SellPrice * ItemCount
DGV1.Rows(ItemLoc).Cells(4).Value = ItemCount
DGV1.Rows(ItemLoc).Cells(5).Value = NewPrice
End If
' next clear textbox1 and set focus to it
TextBox1.Text = ""
TextBox1.Focus()
' compute the total for the recipt
Dim Sum As Decimal = 1
For I = 0 To DGV1.Rows.Count - 1
Sum += DGV1.Rows(I).Cells(5).Value 'here the error happens
Next
TextBox4.Text = Sum
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Error")
End Try
End Sub
The error details:
error: index was out of range.must be non-negative and less than the
size of the collection. parameter name: index vb.net
DGV1 must have fewer cells than 5. When the error occurs, use a breakpoint and the debug watch window to see how many cells there are in DVG1(I). Maybe the first one is created with zero cells?

Bubble Sort logical error VB.NET

This program suppose to sort records(in arySort) in ascending order by last name(index 1 in aryTemp and aryTemp2) and place the result in the list box over the old, preloaded, unsorted records.
It sorts them strangely, I have to click multiple times the Ascending button to get the actual sort result that I suppose to get from clicking the button once.
Why doesn't it sort items with a single mouse click?
The source:
Public Class Form1
Dim FILE_NAME As String = "Students.txt"
Dim numberOfRecords As Integer 'total number of records
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
lstBox.Items.Add(objReader.ReadLine)
numberOfRecords += 1
Loop
objReader.Close()
End If
End Sub
Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
'load all students into array
Dim arySort(numberOfRecords - 1) As String
Dim aryTemp() As String 'holds first record's last name
Dim aryTemp2() As String 'holds second record's last name
For i = 0 To numberOfRecords - 1
arySort(i) = lstBox.Items(i)
Next
Dim temp As String 'holds temporary record
Dim k As Integer
For i = 0 To arySort.Length - 2
aryTemp = Split(arySort(i), " ")
For k = i + 1 To arySort.Length - 1
aryTemp2 = Split(arySort(k), " ")
If aryTemp(1) < aryTemp2(1) Then
temp = arySort(k)
arySort(k) = arySort(i)
arySort(i) = temp
End If
Next
Next
lstBox.Items.Clear()
numberOfRecords = 0
For i = 0 To arySort.Length - 1
lstBox.Items.Add(arySort(i))
numberOfRecords += 1
Next
End Sub
End Class
If you just need to sort your list (as you say in the comment), don't implement your own sort mechanism but use the one of .NET:
' Define how we want to compare items '
Function compareByLastName(ByVal item1 As String, ByVal item2 As String) As Integer
Return String.Compare(item1.Split(" ")(1), item2.Split(" ")(1))
End Function
Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
' load all students into array '
Dim arySort(numberOfRecords - 1) As String
For i = 0 To numberOfRecords - 1
arySort(i) = lstBox.Items(i)
Next
' Use built-in .NET magic '
Array.Sort(arySort, AddressOf compareByLastName)
' Write the values back into your list box '
lstBox.Items.Clear()
numberOfRecords = 0
For i = 0 To arySort.Length - 1
lstBox.Items.Add(arySort(i))
numberOfRecords += 1
Next
End Sub
This uses the built-in quicksort algorithm of the .NET class library. Here's the documentation of the method we are using: Array.Sort(T(), Comparison(Of T)).
compare with my working bubble sort:
Public Sub BubbleSort(ByVal arr() As Integer)
Dim flag As Boolean = False
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To arr.Length - 2 - i
If arr(j + 1) < arr(j) Then
flag = True
Dim temp As Integer = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = temp
End If
Next
If flag = False Then Return ' no swaps =>already sorted
Next
End Sub
I see a two major issues with your algorithm:
It's not bubble sort. Bubble sort swaps adjacent elements, i.e., it swaps i with i+1. You, on the other hand, swap some element i with the first j > i where name(i) < name(j). Maybe you should show us, in pseudo code, which algorithm you are actually trying to implement?
aryTemp contains element i and aryTemp2 contains some element j > i. Why do you swap the elements if aryTemp(1) < aryTemp2(1)? Isn't that already the correct order if you want your elements to be sorted ascending?