Assign the counter number for object name [duplicate] - vb.net

This question already has answers here:
For each textbox loop
(3 answers)
Closed 6 years ago.
I have 60 textboxes in vb and I want to export all of them into one text file. I use this code to do that:
My.Computer.FileSystem.WriteAllText("Filename.txt", TextBox1.Text)
Because I have 60 textboxes so I will take me a long time to do that, I use the For...Next to ease the procedure. I want to have a code like this:
For i as integer = 1 to 60
My.Computer.FileSystem.WriteAllText("Filename.txt", TextBox(i).Text)
Next
Can I do that in vb? Are there any alternative ways to do that? Thanks!

You can create a list of textboxes and add all the needed textboxes to the list. Use foreach loop on the list to access the textboxes one by one and use their text property as you wish.

You can get the TextBoxes, in order using Controls.Find() like this:
Dim fileName As String = "c:\some folder\path\Filename.txt"
Using sw As New System.IO.StreamWriter(fileName)
Dim tb As TextBox
Dim matches() As Control
For i As Integer = 1 To 60
matches = Me.Controls.Find("TextBox" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
tb = DirectCast(matches(0), TextBox)
sw.WriteLine(tb.Text)
End If
Next
End Using
If you simply iterate over the Controls collection the TextBoxes may be returned in a different order (than their name) if you had cut them or copied/pasted some of them when you created the form.

Related

call multiple Items in one loop

In the small project I'm currently working on I have multiple Textboxes I control that all have very similar names (seg11, seg21, se31 etc.) that all use the same function. Is it possible to somehow call them all with a for loop?
I think it should look something like this but I'm not sure how I can make the different TextBox names work:
For n As Integer = 0 To 5
i = n
function(seg"n"1)
Next
You can get controls by with use parental control control function whose parameter can be the name of the desired control.
The correct way to string concat, use the & symbol, e.g: "seg" & n & "1"
The correct code for your problem:
For n As Integer = 0 To 5
Dim ctr As Control = Me.Controls("seg" & n & "1")
If ctr IsNot Nothing Then
Debug.WriteLine(ctr.Text)
End If
Next

Filter DataGridView across all columns

Sorry for my bad English. I am an old German man, I want to filter a DGV across all columns. In the Moment I use following filter:
Dim Such_Spalte = Me.DtS_DGV.DTT_1.article_1Column.ColumnName
But I have 10 Columns (article_1 to Article_10)
If as an example Sugar is in column 1,3,5 I want to see all records where sugar occurs.
I hope this is understandable
You seem to be using strongly typed datasets and as such I would expect that your datagridview is bound through a BindingSource (the windows forms designer sets it up this way, and my presumption is that you used te designer to do your binding)
If your datagridview is indeed bound through a bindingsource:
Dim bs = DirectCast(datagridviewX.DataSource, BindingSource)
Dim sb = New StringBuilder() 'it will hold the filter string
For Each col in DtS_DGV.DTT_1.Columns
sb.AppendFormat("[{0}] = '{1}' OR ", col.ColumnName, "Sugar")
Next col
sb.Length -= 3 'remove the trailing OR
bs.Filter = sb.ToString()
If your datagridview is bound direvtly to the table, it will have attached to the table's DefaultView property, a DataView, which also has a Filter that works in the same way. If this is the case, do the same thing with the loop to build the filter string, and then:
DtS_DGV.DTT_1.DefaultView.Filter = sb.ToString()

Iterate over numbered textboxes [duplicate]

This question already has answers here:
Can I use variables to control which PictureBox I am using?
(2 answers)
Closed 5 years ago.
I created 10 textboxes which are entitled Txtb_1, Txtb_2.... and a table with 10 values. For example Dim table() as integer = {0,1,2,3....}
The first 5 textbox will contain a value as an integer. The other 5, the value will be incremented by x.
I want to show on screen the comparison before and after.
All my variables are declared as string for Txtb_1.,Txtb_2 etc.
For the variable Txtb_6 to Txtb_10, is it possible to put them in a for loop and change only the number in the name of the variable?
What i want is to be able to simplify my task.
For example :
for i = 6 to 10
Txtb_**i**.text = table(x)
next
So the loop will go from Txtb_6 to Txtb_10, reducing the coding.
For this you'll be able to use the Control.FindControl function.
Dim curControl As Control = Nothing
For i = 6 To 10
curControl = FindControl($"Txtb_{i}") 'or string format or &
If (Not curControl Is Nothing)
' your logic
(curControl As TextBox).Text = table(x) 'prob want to exception handle
End If
Next
More info here: https://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx
Ways to cast: https://www.codeproject.com/Articles/5044/Cheat-Sheet-Casting-in-VB-NET-and-C

How to generate a random selection from SQL DB to a listbox using 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.

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.