How to generate a random selection from SQL DB to a listbox using vb.net - vb.net

I am trying to write a program that will allow a user to generate a random list of names. I have a gridview of names from a SQL Db when the form launches. Is it possible to generate a random list from the names in the gridview or does that have to come from another Sql Connection string and reference different parameters? I was trying to display random names from the gridview to a listbox. Thank you.
Here is the code that I have been trying to experiment with:
Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
Dim listCount As Integer
Dim i As Integer = 0
Dim rnd As New Random
Dim listselection As Integer
listCount = grdEmployees.
Do While i < CInt(grdEmployees.Text)
'randomize selection
listselection = rnd.Next(0, grdEmployees.Items.Count)
lstSelected.Items.Add(grdEmployees.Items(listselection))
grdEmployees.Items.RemoveAt(listselection)
'increment i
i += 1
Loop
txtQuantity.Text = String.Empty 'Clears box after entry
End Sub

You could do it through your SQL query:
SELECT TOP 25 SomeField FROM SomeTable ORDER BY RAND()
Or through your managed code. Which is best depends on the size of the table and where you want the sorting to be done. If you prefer to sort on the server, or locally.

Related

Using a LINQ query to populate a combo box with data from an access database

In VB.Net:
I am trying to populate a combo box on my form using data from a MS Access database. Specifically; taking all of the last names from the database, sorting them in ascending order in an output list which I named players and then adding each item in players to my combo box (cboPlayer).
Public Sub GetPlayers()
Dim PlayerLastName As New List(Of String)
PlayerLastName.Add("Smith")
PlayerLastName.Add("Hill")
PlayerLastName.Add("Beyer")
PlayerLastName.Add("Wilson")
PlayerLastName.Add("Hudson")
PlayerLastName.Add("van Zegeren")
PlayerLastName.Add("Bibbs")
PlayerLastName.Add("Muller")
PlayerLastName.Add("Pierce")
PlayerLastName.Add("Henry")
PlayerLastName.Add("Johnston")
Dim Players = From Last In PlayerLastName
Order By Last Ascending
Select Last
cboPlayer.Items.Add(Players.ToString)
cboPlayer.SelectedItem = 0
I know this isn't exactly correct but not positive what direction to head in. When I run the program the combo box is populated with System.linq.enumerated.
Any ideas what that might mean or what I am doing incorrectly?
Maybe over thinking it just a little? Why not try without the linq, List has a sort function. Also just bind PlayerLastName to the combobox.
Public Sub GetPlayers()
Dim PlayerLastName As New List(Of String)
PlayerLastName.Add("Smith")
PlayerLastName.Add("Hill")
PlayerLastName.Add("Beyer")
PlayerLastName.Add("Wilson")
PlayerLastName.Add("Hudson")
PlayerLastName.Add("van Zegeren")
PlayerLastName.Add("Bibbs")
PlayerLastName.Add("Muller")
PlayerLastName.Add("Pierce")
PlayerLastName.Add("Henry")
PlayerLastName.Add("Johnston")
PlayerLastName.Sort()
cboPlayers.DataSource = PlayerLastName
cboPlayers.SelectedIndex = -1
End sub
Edit:
or if you still want to us linq then, you need to change the linq return of IEnumerable to a List...
Dim Players = From Last In PlayerLastName
Order By Last Ascending
Select Last
ComboBox1.DataSource = Players.ToList
ComboBox1.SelectedIndex = -1

Multiplying multiple texboxes

I am creating a menu application, I have at the moment 3 textboxes, textbox1 is price, textbox2 is quantity and textbox3 is total. I have successfully written the code to calculate the price of an item depending on the quantity they need. The code i have right now:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox8.Text = CStr(Val(TextBox6.Text) * Val(TextBox7.Text))
End Sub
Now what I need is that I will have more items say 10 along with textboxes beside as quantity which makes 20 textboxes and one total textbox. How can I write the code so that it calculates every textbox as well as null values say if out of the 10 items i want only 2 items 1 per quantity into the total value.
Thanks
First, i strongly suggest to use .NET methods instead of old VB methods. I also would set OPTION STRICT to On in general which avoids "magical" conversions done for you by the runtime. Instead you have to specify the correct types which is a good thing since it can prevent errors on runtime and it also helps to learn the .NET types and methods.
I would add those TextBoxes all to the same container-control (like a Panel or something similar). I also suggest to use more meaningful names for your controls(f.e. TxtTotal for the total-textbox).
So if all price-textboxes' names start with TxtPrice (f.e. TxtPrice1 etc) and all quantity-TextBoxes start with TxtQuantity (f.e. TxtQuantity1 etc), this LINQ query approach will work:
Dim allTextBoxes = PriceQuantityPanel.Controls.OfType(Of TextBox)()
Dim allPrices = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtPrice")
Dim allQuantities = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtQuantity")
Dim price As Decimal
Dim invalidPrices = From txt In allPrices
Where Not Decimal.TryParse(txt.Text, price)
If invalidPrices.Any() Then
MessageBox.Show("Please enter valid prices(Decimal)!")
Return
End If
Dim quantity As Int32
Dim invalidQuantities = From txt In allQuantities
Where Not Int32.TryParse(txt.Text, quantity)
If invalidQuantities.Any() Then
MessageBox.Show("Please enter valid quantities(Integer)!")
Return
End If
Now you can "join" the pairs of price and quantity textboxes by the number-suffix:
Dim query = From txtP In allPrices
Join txtQ In allQuantities
On txtP.Name.Substring("TxtPrice".Length) Equals txtQ.Name.Substring("TxtQuantity".Length)
Select New With {.Price = Decimal.Parse(txtP.Text), .Quantity = Int32.Parse(txtQ.Text)}
Dim totalSum As Decimal = query.Sum(Function(x) x.Price * x.Quantity)
TxtTotal.Text = totalSum.ToString()

Search Listbox and return specific number of items defined in another field - VB.net

I'm running a search query that pulls the search string from one text box, then searches a listbox for the string and displays the results in a second listbox. I would like to define the number of items that it returns based on a second text box. So far I am able to get all list items with be given string to show in the second box. But I have yet to get it to limit the search to 1 item etc. The functional code I've used to show all results is:
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
lstResults.Items.Clear()
If txtSearch.Text.Length > 0 Then
For index As Integer = 0 To lstCountries.Items.Count - 1
Dim txt = lstCountries.Items(index).ToString()
If txt.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(txt)
End If
Next
End If
I've tried using while txtnumber.text > 1 then ahead of this but seem to have created a loop. Any ideas as to what I'm missing?
The datasource is going to have the final say on how many results there are. If the user specifies 3 and there are only 2 in the source, thats all you will get. Something like this will move the results from one to the other until the max is found:
Dim Max as integer = Convert.Toint32(txtNumber.Text)
Dim Count as integer = 0
lstResults.Items.Clear()
For index As Integer = 0 To lstCountries.Items.Count - 1
if lstCountries.Items(index).StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
lstResults.Items.Add(lstCountries.Items(index))
count += 1
end if
' exit the loop if we found enough
If count>= Max Then
Exit For
End If
Next
If the listbox just contains text (strings) then you do not need the ToString: lstCountries.Items(index).StartsWith(strSearch). Basically, you need to exit the loop once the user desired number have been found OR if you run out of data...if I understood right. while txtnumber.text > 1 would not work because textboxes contain strings not numerics (23 is not the same as "23").
The LINQ extensions would work well here as well:
lstResults.Items.AddRange((From item In lstCountries.Items
Let strItem As String = item.ToString
Where strItem.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase)
Select strItem).Take(Integer.Parse(txtnumber.Text)).ToArray)
This assumes that all your data has already been validated.

Need help on generating random words for a search bot VB 2010

So i am trying to make a search bot that uses random words. I am using an increment value with Minimum of 2 and a Maximum of 30 for the number of searches to do at a time.
I was thinking something like this but it also seems like it would not be as good since it would not really generate a random string which would be a lot better:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SE As String
SE = NumericUpDown1.Value
Select Case SE
Case "2"
End Select
End Sub
If anybody could help me It would be greatly appreciated.
You can use the Random class and it's method Next to create random numbers.
Dim rnd As New Random()
Dim SE As String = rnd.Next(2, 31).ToString()
Note that the random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated.
So if you want to use a loop, you should not create the random instance in the loop but outside of it.
However, i'm not sure what kind of words you want to create. I doubt that you want numeric strings between "2" and"30" even if your code suggests it.
Update according to your comment
The 2 and 30 are how many searches to do at a time, i want to
randomize the word(s) out of
lets say a list of 60-70 words
So i assume that you want a random number(between 2-30)of random words from a list of strings:
Dim words = {"word 1", "word 2", "word 3", ".....", "word 60"}
Dim rnd As New Random()
Dim howMany As Int32 = rnd.Next(2, 31)
Dim randomWords As New List(Of String)
For i As Int32 = 1 To howMany
Dim nextRandomIndex = rnd.Next(0, words.Count)
randomWords.Add(words(nextRandomIndex))
Next

VB.net Can't get output to appear in my listbox. Beginners Question

Trying to get the user to put 3 numbers in 3 text boxes and get the average.
Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAverage.Click
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Integer
average = (a + b + c) / 3
lstOutput.Text = average
End Sub
Try changing the type of average from Integer to Double
Dim average as Double
Right now you're trying to store the Average in an Integer which can only hold a whole number. Averages tend to be non-whole numbers and need a data type that can represent that. Double is good for most situations. That should fix your problem.
EDIT OP mentioned that lstOutput is a ListBox
This is one of the confusing things with WinForms. Even though every single control has a Text property, not all of them actually do anything. They only apply to elements that directly display a single text block or value. Ex Button, Label, etc ...
A ListBox on the other hand displays a group of items. You want to add a new item to the list.
lstOutput.Items.Add(average.ToString())
The Text property of a list box will get or set the selected item. You haven't added your average to the listbox yet.
Try:
lstOutput.Items.Add(average)
Are you sure that txtOne.text txtTwo.text and txtThree.txt will always be an integer value?
You might need to also change the a,b,c vars to Doubles and check that the user didn't supply non-numeric values.
If the user puts "one" in the txtOne textbox, you'll get an exception kablowee.
(air coding here)
dim a as new double
try
if isnumeric(txtOne.text.tostring.trim) then
a = cdbl(txtOne.text.tostring.trim)
end if
'repeat for b and c ...
catch ex as exception
messagebox.show(ex.message.tostring)
end try
And, I'm not sure if I'm right about this, (maybe someone will enlighten me) but does .NET consider type conversion from string to int differently in these two cases
a = cint(txtOne.text)
and
a = cint(txtOne.text.tostring)
???