Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
This Code is too repetitive! I have to re write this code up to twenty! Can you guys help me covert this into a loop that wil just move from textbox1, to 2 to 3 and so on?
If CheckBox1.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox1.Text & Environment.NewLine)
End If
If CheckBox2.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox2.Text & Environment.NewLine)
End If If CheckBox1.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox1.Text & Environment.NewLine)
End If
If CheckBox2.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox2.Text & Environment.NewLine)
End If
If CheckBox3.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox3.Text & Environment.NewLine)
End If
If CheckBox4.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox4.Text & Environment.NewLine)
End If
If CheckBox5.Checked = True Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(frmLunchBoxMenu.LineNumber.ToString + ".) An order of " + CheckBox5.Text & Environment.NewLine)
End If
This works, thanks for the help guys, the issue was the direct cast. Solved:
Public Class frmBeverages
Dim Range As Integer = 0
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
While Range < 14
Range = Range + 1
Dim chk As CheckBox =
DirectCast(Me.Controls("Checkbox" & CStr(Range)), CheckBox)
If chk.CheckState = CheckState.Checked Then
frmLunchBoxMenu.LineNumber = frmLunchBoxMenu.LineNumber + 1
frmLunchBoxMenu.txtOrder.AppendText(CStr(frmLunchBoxMenu.LineNumber) & ".) An order of " & chk.Text & Environment.NewLine)
End If
End While
Close()
End Sub
End Class
Dim strOutput As String = ""
Dim intLineNumber As Integer = 0
For Each ctl As Control In Me.Controls
If TypeOf ctl Is CheckBox Then
Dim chk As CheckBox = DirectCast(ctl, CheckBox)
If chk.Checked Then
intLineNumber += 1
strOutput &= intLineNumber.ToString + ".) An order of " + ctl.Text & vbCrLf
End If
End If
Next ctl
txtOrder.Text = strOutput
...but you should also consider using the CheckedListBox control instead. That will allow your menu to be dynamically loaded (loaded from a text file or a database), and you won't need to manage multiple checkbox controls.
Here's the CheckedListBox version...
Public Class frmLunchBoxMenu
'Add a CheckedListBox, a Button, and a TextBox named txtOrder to the form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.Add("Hamburger")
CheckedListBox1.Items.Add("Pizza")
CheckedListBox1.Items.Add("Cola")
CheckedListBox1.Items.Add("Chips")
CheckedListBox1.Items.Add("Hot dog")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strOutput As String = ""
Dim intLineNumber As Integer = 0
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
If CheckedListBox1.GetItemChecked(i) Then
intLineNumber += 1
strOutput &= intLineNumber.ToString + ".) An order of " + CheckedListBox1.Items(i).ToString & vbCrLf
End If
Next i
txtOrder.Text = strOutput
End Sub
End Class
This could be a way to do it:
Dim Range As Integer() =
Enumerable.Range(1, 20).ToArray
For Each n As Integer In Range
Dim chk As CheckBox =
DirectCast(Me.Controls("Checkbox" & CStr(n)), CheckBox)
' Specify above the right ControlCollection if needed.
If chk.Checked Then
With frmLunchBoxMenu
.LineNumber += 1
.txtOrder.AppendText(CStr(frmLunchBoxMenu.LineNumber) &
".) An order of " & chk.Text &
Environment.NewLine)
End With
End If
Next n
Related
I fixed the tag, thought VBA meant visual-basic, but I'm naive in this realm.
I'm not sure what I'm doing wrong here..
I think I'm forgetting input validation near readfile() but I'm not sure how to code it.. when I run the program I get a error with currentrecord(4). Please help.. .-.
Module Module1
' IMPUT VARIABLES:
Private ProductNumberInteger As Integer
Private ProductDescriptionString As String
Private WholeSalePriceDecimal As Decimal
Private MarkupCodeInteger As Integer
Private QuantitySoldInteger As Integer
' CALCULATED VARIABLES AFTER PROCESSING:
Private CalculatedMarkupAmountDecimal As Decimal '
Private CalculatedRetailPriceDecimal As Decimal
Private CalculatedDiscountAmountDecimal As Decimal
Private CalculatedDiscountedPriceDecimal As Decimal
Private CalculatedTotalEarnedDecimal As Decimal
Private CalculatedTotalProfitDecimal As Decimal
' ASSIGNED FIELDS:
Private MarkupRateDecimal
Private DiscountPercentRateDecimal
' CONSTANT VARIABLES:
Private MARKUP_CODE_1_DECIMAL As Decimal = 1.05
Private MARKUP_CODE_2_DECIMAL As Decimal = 1.07
Private MARKUP_CODE_3_DECIMAL As Decimal = 1.1
Private MARKUP_CODE_4_DECIMAL As Decimal = 1.2
Private MARKUP_CODE_5_DECIMAL As Decimal = 1.25
Private CurrentRecord() As String
Private TURKEYSALESFILE As New Microsoft.VisualBasic.FileIO.TextFieldParser("THANKSWk44.txt")
' ACCUMULATORS
Private AccumFinalTotalWholesalePriceDecimal As Decimal
Private AccumFinalTotalMarkupAmountDecimal As Decimal
Private AccumFinalTotalProfitDecimal As Decimal
Private AccumFinalTotalNumberOfItemsSoldThisWeekInteger As Integer
' FINAL CALCULATIONS AT EOF:
Private FinalProfitRatioDecimnal As Decimal
Private FinalAverageMarkupDecimal As Decimal
' PAGINATION CODE:
Private PageSizeInteger As Integer = 15
Private LineCounterInteger As Integer = 99
Private PageNumberInteger As Integer = 1
Private RecordSelectedBoolean As Boolean
'--------------------------------------------------------------------------------------------------------------
Sub Main() ' PROGRAM STARTS HERE
Housekeeping()
Do While Not TURKEYSALESFILE.EndOfData
Call ProcessRecords()
Loop
Call EndOfJob() ' PROGRAM ENDS HERE AFTER LOOP. EOJ CHECKS FOR EOF STATUS. 1/1 = EOF
End Sub
'--------------------------------------------------------------------------------------------------------------
' LEVEL TWO PROCESSES
Private Sub Housekeeping()
SetFileDelimiter() ' SETS FILE TYPE AS DELIMITED AND ADDS A COMMA
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub ProcessRecords()
ReadFile()
RecordSelection()
If RecordSelectedBoolean = True Then
DetailCalculations()
AccumulateTotals()
WriteDetailLine()
End If
'--------------------------------------------------------------------------------------------------------------
End Sub
Private Sub EndOfJob() ' PROGRAM END
FinalCalculations()
FinalOutput()
CloseFile()
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub SetFileDelimiter()
TURKEYSALESFILE.TextFieldType = FileIO.FieldType.Delimited
TURKEYSALESFILE.SetDelimiters(",") ' ADDS A COMMA
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub ReadFile() ' READS EACH RECORD IN ORDER
'Try
' TURKEYSALESFILE 'Do something dangerous
'Catch ex As System.Exception 'catch any error
' 'Handle the error here
'End Try
'Try
'Catch
' Console.WriteLine("ERROR")
'End Try
CurrentRecord = TURKEYSALESFILE.ReadFields()
ProductNumberInteger = CurrentRecord(0)
ProductDescriptionString = CurrentRecord(1)
WholeSalePriceDecimal = CurrentRecord(2)
MarkupCodeInteger = CurrentRecord(3)
QuantitySoldInteger = CurrentRecord(4)
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub RecordSelection()
If ProductNumberInteger = 100 - 300 Or ProductNumberInteger = 400 - 500 Or ProductNumberInteger = 600 - 700 Then
RecordSelectedBoolean = True
End If
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub DetailCalculations() ' GENERATES CALCULATIONS THAT IS TO BE APPLIED TO THE DATA SPECIFIED
CalculatedMarkupAmountDecimal = WholeSalePriceDecimal * MarkupRateDecimal
CalculatedRetailPriceDecimal = WholeSalePriceDecimal + CalculatedMarkupAmountDecimal
CalculatedDiscountAmountDecimal = CalculatedRetailPriceDecimal * DiscountPercentRateDecimal
CalculatedDiscountedPriceDecimal = CalculatedRetailPriceDecimal - CalculatedDiscountAmountDecimal
CalculatedTotalEarnedDecimal = CalculatedDiscountedPriceDecimal * QuantitySoldInteger
CalculatedTotalProfitDecimal = CalculatedTotalEarnedDecimal - (QuantitySoldInteger * WholeSalePriceDecimal)
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub DetermineMarkupCode()
Select Case MarkupCodeInteger
Case Is = 1
MarkupCodeInteger = MARKUP_CODE_1_DECIMAL
Case = 2
MarkupCodeInteger = MARKUP_CODE_2_DECIMAL
Case = 3
MarkupCodeInteger = MARKUP_CODE_3_DECIMAL
Case = 4
MarkupCodeInteger = MARKUP_CODE_4_DECIMAL
Case Else
MarkupCodeInteger = MARKUP_CODE_5_DECIMAL
End Select
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub DetermineDiscountAmount()
If QuantitySoldInteger = 0 - 10 Then
DiscountPercentRateDecimal = 1.0
Else
If QuantitySoldInteger = 11 - 25 Then
DiscountPercentRateDecimal = 10.0
Else
If QuantitySoldInteger = 26 - 40 Then
DiscountPercentRateDecimal = 12.5
Else
If QuantitySoldInteger = 41 - 50 Then
DiscountPercentRateDecimal = 20.0
Else
DiscountPercentRateDecimal = 25.5
End If
End If
End If
End If
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub AccumulateTotals()
AccumFinalTotalWholesalePriceDecimal += WholeSalePriceDecimal
AccumFinalTotalMArkupAmountDecimal += CalculatedMarkupAmountDecimal
AccumFinalTotalProfitDecimal += CalculatedTotalProfitDecimal
AccumFinalTotalNumberOfItemsSoldThisWeekInteger += 1
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub WriteDetailLine()
If LineCounterInteger > PageSizeInteger Then
WriteHeaders()
End If
' DETAIL LINE OUTPUT
Console.WriteLine(ProductNumberInteger.ToString().PadRight(3) &
Space(1) & ProductDescriptionString.PadLeft(12) &
Space(1) & WholeSalePriceDecimal.ToString("N").PadLeft(5) &
Space(2) & MarkupCodeInteger.ToString() &
Space(1) & CalculatedMarkupAmountDecimal.ToString("N").PadLeft(5) &
Space(2) & CalculatedRetailPriceDecimal.ToString("N").PadLeft(6) &
Space(1) & DiscountPercentRateDecimal.ToString("n0") &
Space(1) & CalculatedDiscountAmountDecimal.ToString("N").PadLeft(5) &
Space(2) & QuantitySoldInteger.ToString().PadLeft(2) &
Space(2) & CalculatedDiscountedPriceDecimal.ToString("N").PadLeft(6) &
Space(1) & CalculatedTotalEarnedDecimal.ToString("N").PadLeft(8) &
Space(2) & CalculatedTotalProfitDecimal.ToString("N").PadLeft(6))
LineCounterInteger += 1
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub WriteHeaders()
Console.WriteLine("Page" & PageNumberInteger.ToString("n0").PadLeft(3) &
Space(18) & "Sales and Profit Report for")
Console.WriteLine(Space(25) & "Thanks for Thanksgiving, Inc.,")
Console.WriteLine(Space(32) & "by Nathaniel Kulinski")
Console.WriteLine()
Console.WriteLine("Item Desc" &
Space(6) & "WhlSale" &
Space(1) & "-Markup-" &
Space(2) & "Retail" &
Space(1) & "-Discount-" &
Space(1) & "Qty" &
Space(2) & "Discnt" &
Space(4) & "Total")
Console.WriteLine("Num" &
Space(14) & "Price" &
Space(1) & "Code" &
Space(1) & "Amt" &
Space(2) & "Price" &
Space(5) & "%" &
Space(3) & "Amt" &
Space(1) & "Sld" &
Space(3) & "Price" &
Space(3) & "Earned" &
Space(2) & "Profit")
Console.WriteLine()
LineCounterInteger = 1
PageNumberInteger += 1
End Sub
'--------------------------------------------------------------------------------------------------------------
Private Sub FinalCalculations()
FinalProfitRatioDecimnal = AccumFinalTotalProfitDecimal / AccumFinalTotalWholesalePriceDecimal
FinalAverageMarkupDecimal = AccumFinalTotalMarkupAmountDecimal / AccumFinalTotalNumberOfItemsSoldThisWeekInteger
End Sub
Private Sub FinalOutput()
Console.WriteLine()
Console.WriteLine(Space(1) & "FINAL TOTALS:")
Console.WriteLine(Space(5) & "Wholesale Price" &
Space(6) & AccumFinalTotalWholesalePriceDecimal.ToString("C").PadLeft(9))
Console.WriteLine(Space(5) & "Markup Amount" &
Space(8) & AccumFinalTotalMarkupAmountDecimal.ToString("C").PadLeft(9))
Console.WriteLine(Space(5) & "Profit" &
Space(15) & AccumFinalTotalProfitDecimal.ToString("C").PadLeft(9))
Console.WriteLine(Space(5) & "Items Sold" &
Space(12) & AccumFinalTotalNumberOfItemsSoldThisWeekInteger.ToString("N").PadLeft(5))
Console.WriteLine()
Console.WriteLine(Space(5) & "Profit Ratio" &
Space(11) & FinalProfitRatioDecimnal.ToString("C").PadLeft(7))
Console.WriteLine(Space(5) & "Avg Markup Per Item" &
Space(5) & FinalAverageMarkupDecimal.ToString("C").PadLeft(6))
End Sub
Private Sub CloseFile() ' END OF PROGRAM
Console.WriteLine()
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Press Enter To Close Window") ' PROMPT FOR THE USER TO CLOSE THE PROGRAM
Console.ReadLine()
TURKEYSALESFILE.Close()
End Sub
End Module
I was able to get the code to output some stuff, but it was incomplete. I think there is a issue with the imput file (this is an assignment), but I'm not sure how to fix it.
I am trying to develop a simple bulk copy program that polls a given folder for files at specified intervals.
The code looks perfect. My output gives a great recursive list of files, but when I go to actually move them according to the list, every file I scanned is locked. I have tried garbage collecting, disposing, exiting subs at certain points, debugging at certain points...
Please take a look at my code. When MoveFile is called, everything is locked.
Imports System
Imports System.IO
Public Structure FileStructure
Dim Enumerator As Integer
Dim SPath As String
Dim DPath As String
Dim Name As String
Dim FileSize As Long
Dim IsFile As Short
Dim SourceFullName As String
Dim DestFullName As String
End Structure
Public Class StagingDriveCoordinator
Dim FilesScanned As FileStructure()
Dim ScanCount As Integer = -1
Private Sub ScanAll(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
' ---------------------- Create the appropriate directories --------------------------------
' Create source path
If Not System.IO.Directory.Exists(sourcePath) Then
System.IO.Directory.CreateDirectory(sourcePath)
End If
' If the destination folder doesn't exist then create it
If Not System.IO.Directory.Exists(destinationPath) Then
System.IO.Directory.CreateDirectory(destinationPath)
End If
' ------------------------------------------------------------------------------------------
Dim AddSize As Integer = 0
'Figure out how much to resize the array this iteration of ScanAll
If FilesScanned IsNot Nothing Then
AddSize = FilesScanned.Count + sourceDirectoryInfo.GetFileSystemInfos.Length
Else
AddSize = sourceDirectoryInfo.GetFileSystemInfos.Length
End If
'Resize the array
Array.Resize(FilesScanned, AddSize)
For Each FileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
ScanCount += 1
FilesScanned(ScanCount).Enumerator = ScanCount
FilesScanned(ScanCount).SPath = sourcePath.ToString
FilesScanned(ScanCount).DPath = destinationPath.ToString
FilesScanned(ScanCount).Name = FileSystemInfo.Name.ToString
If TypeOf FileSystemInfo Is System.IO.FileInfo Then
FilesScanned(ScanCount).FileSize = DirectCast(FileSystemInfo, FileInfo).Length
FilesScanned(ScanCount).IsFile = 1
Else
FilesScanned(ScanCount).FileSize = 9223372036854775807
FilesScanned(ScanCount).IsFile = 0
End If
FilesScanned(ScanCount).SourceFullName = System.IO.Path.Combine(sourcePath, FileSystemInfo.Name).ToString
FilesScanned(ScanCount).DestFullName = System.IO.Path.Combine(sourcePath, FileSystemInfo.Name).ToString
txtOutput.Text += FilesScanned(ScanCount).Enumerator & vbTab & FilesScanned(ScanCount).SourceFullName & vbNewLine
If FilesScanned(ScanCount).IsFile = 0 Then
'Debug
txtOutput.Text += vbNewLine & "Recursively scanning subfolder " + FilesScanned(ScanCount).Name & "..." + vbNewLine + vbNewLine
'Recursively call the main scanner.
ScanAll(FilesScanned(ScanCount).SourceFullName, FilesScanned(ScanCount).DestFullName)
End If
Next
End Sub
Private Sub MoveFile(ByVal Source, ByVal Destination, ByVal filesize)
Try
File.Copy(Source, Destination, True)
txtOutput.Text += "Moving file... Source: " & Source & ". Filesize: " & filesize.ToString & vbNewLine
txtOutput.Text += "Destination: " & Destination & vbNewLine & vbNewLine
File.Delete(Source)
Catch ex As Exception
txtOutput.Text += "File " & Source & " is locked." & vbNewLine
End Try
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Select Case cmbPollingFrequency.SelectedItem
Case "5 Seconds"
Timer1.Interval = 5000
Case "30 Seconds"
Timer1.Interval = 30000
Case "1 Minute"
Timer1.Interval = 60000
Case "5 Minutes"
Timer1.Interval = 300000
Case "15 Minutes"
Timer1.Interval = 900000
Case "30 Minutes"
Timer1.Interval = 1800000
Case "1 Hour"
Timer1.Interval = 3600000
Case Else
MsgBox("You must select an interval.")
End Select
Timer1.Start()
End Sub
Private Sub TimerTick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
txtOutput.Text += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & vbNewLine
txtOutput.Text += "Scanning Filesystem..." + vbNewLine + vbNewLine
'Scan the file system.
ScanAll(cmbStaging.Text, cmbBackup.Text)
txtOutput.Text += vbNewLine
txtOutput.Text += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & vbNewLine
txtOutput.Text += " ------------- Scan cycle completed. --------------- " & vbNewLine & vbNewLine
txtOutput.Text += "Sorting by filesize..." & vbNewLine & vbNewLine
' Sort the file list by size.
FilesScanned = FilesScanned.OrderBy(Function(x) x.FileSize).ToArray
txtOutput.Text += "Done." & vbNewLine & vbNewLine
txtOutput.Text += "Moving smallest files first..." & vbNewLine & vbNewLine
For Each FileElement In FilesScanned
If FileElement.IsFile > 0 Then
'file.FileSize only needed to pass size to text output
MoveFile(FileElement.SourceFullName, FileElement.DestFullName, FileElement.FileSize)
End If
Next
FilesScanned = Nothing
ScanCount = -1
Timer1.Start()
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Timer1.Stop()
End Sub
End Class
I found the problem. The IO system was NOT locking the file. I was trying to copy it to the SAME directory...
FilesScanned(ScanCount).SourceFullName =
System.IO.Path.Combine(sourcePath, FileSystemInfo.Name).ToString
FilesScanned(ScanCount).DestFullName =
System.IO.Path.Combine(sourcePath, FileSystemInfo.Name).ToString
This should have been:
FilesScanned(ScanCount).SourceFullName =
System.IO.Path.Combine(sourcePath, FileSystemInfo.Name).ToString
FilesScanned(ScanCount).DestFullName =
System.IO.Path.Combine(destinationPath, FileSystemInfo.Name).ToString
Once I changed it, everything worked perfectly.
Im working on a code that has a TextBox, A Button and a Datagrid view.
I want to Display "Data Not Exist" when a value in TextBox is not present on the DataGridView when i press the button.
This is my code so far
If DataGridView1.Rows.Contains(TextBox1.Text) = False Then
MessageBox.Show("Data Not Exist!")
End If
You need to loop through all rows and columns
Dim isFound As Boolean = False
For Each row As GridViewRow In DataGridView1.Rows
for i As Integer = 0 to DataGridView1.Columns.Count -1
If row.Cells[i].Text = TextBox1.text Then
isFound = True
exit for
End If
Next
Next
If (isFound) Then
MessageBox.Show("Data Exists!")
Else
MessageBox.Show("Data Not Exists!")
EndIf
You can do it easily with either using a LINQ or a ForLoop
This code will search all matches it will find across the DataGridView and will prompt in which Row and Column it sees the match.
With a ForLoop, you need to run a loop for Column and for the Row.
Private Sub SearchUsingForLoop()
Dim resultString As String = Nothing
For x = 0 To DataGridView1.ColumnCount - 1
For y = 0 To DataGridView1.RowCount - 1
If DataGridView1.Item(x, y).Value.ToString.ToUpper = txtSearch.Text.ToUpper Then
resultString &= " - Column " & x + 1 & " Row " & y + 1 & vbCrLf
End If
Next
Next
If resultString <> Nothing Then
resultString = txtSearch.Text & " found in : " & vbCrLf & resultString
Else
resultString = "Data does not exist."
End If
MsgBox(resultString)
End Sub
Do remember that index of DatagridViewRow and DatagridViewColumn starts with 0.
Another way of doing this is by LINQ:
Private Sub SearchUsingLINQ()
Dim resultSet = From dgRow As DataGridViewRow In Me.DataGridView1.Rows, _
dgCell As DataGridViewCell In dgRow.Cells _
Where dgCell.Value.ToString.ToUpper = txtSearch.Text.ToUpper _
Select dgCell
Dim resultString As String = Nothing
If resultSet.Count > 0 Then
resultString = txtSearch.Text & " found in :" & vbCrLf
For Each dgCells In resultSet
resultString &= " - Column " & dgCells.ColumnIndex + 1 & " Row " & dgCells.RowIndex + 1 & vbCrLf
Next
End If
If resultString <> Nothing Then
MsgBox(resultString)
Else
MsgBox("Data does not exist.")
End If
End Sub
Feel free to use any of those. But I suggest you to study iterating a DataGridView first.
Everything I read points me to the need to run my "CollectSample" function in a backgroundworker1 but using all the samples I can't figure it out or compile. Because I am very new to vb, and not a strong programmer, I can't figure out how to invoke, or use background worker in the following code. A quick summary, I am calling realterm as a process and it opens and closes just fine, but locks out win form and because its in a loop of 16, I can't breakout if needed? Any help or guidance would be appreciated.
Private Sub Button35_Click(sender As Object, e As EventArgs) Handles Button35.Click
ProgressBar2.Visible = True
ProgressBar2.Value = 0
For i As Integer = 17 To 32
DirectCast(Me.Controls.Find("Button" & i, True)(0), Button).Visible = False
Next
For Bindex = 17 To 32
Dim Counter As Integer = 0
Dim Tone As Integer = TextBox1.Text
Dim Duration As Integer = TextBox2.Text
Duration = Duration * 2
For Counter = 1 To Duration
Counter = Counter + 1
NtBeep(Tone, 200) 'f,d
Next
CollectSample("SAMPLE" & Bindex - 16 & ".txt") 'subtracting the first 16
ProgressBar2.PerformStep()
CheckSample("SAMPLE" & Bindex - 16 & ".txt")
DirectCast(Me.Controls.Find("Label" & Bindex, True)(0), Label).Visible = True
DirectCast(Me.Controls.Find("Button" & Bindex, True)(0), Button).Visible = True
If SampleFlag = 1 Then 'error readiing from instument
DirectCast(Me.Controls.Find("Label" & Bindex, True)(0), Label).Text = "Er00"
DirectCast(Me.Controls.Find("Button" & Bindex, True)(0), Button).Text = "Er00"
End If
If SampleFlag = 2 Then 'sample count error
DirectCast(Me.Controls.Find("Label" & Bindex, True)(0), Label).Text = IncSamp
DirectCast(Me.Controls.Find("Button" & Bindex, True)(0), Button).Text = IncSamp
End If
If SampleFlag = 0 Then 'sample good
If SendMyAvg <> 0 Then
SendMyAvg = Math.Round(SendMyAvg, 2)
' MessageBox.Show("Button" & Bindex & " / " & SendMyAvg)
DirectCast(Me.Controls.Find("Label" & Bindex, True)(0), Label).Text = SendMyAvg
DirectCast(Me.Controls.Find("Button" & Bindex, True)(0), Button).Text = SendMyAvg
End If
End If
Next
End Sub
Private Sub CollectSample(ByVal Samplefile As String) 'call realterm, close realterm
NtBeep(500, 200) 'f,d
'http://www.dotnetperls.com/process-vbnet
Dim p As New ProcessStartInfo
p.FileName = "C:\Program Files (x86)\BEL\Realterm\realterm.exe"
p.Arguments = "C:\Program Files (x86)\BEL\Realterm\realterm.exe Baud=4800 Data=7E2 Port=" & USBPort & " timestamp=4 capfile=C:\IMAX_Ware_V2\LS100Cap\""" & targetName & """ capsecs=35 capture=1 Sendfile=""" & sourceName & """ Senddly=3000 Sendrep=10 CapQuit"
p.WindowStyle = ProcessWindowStyle.Hidden
Dim myProcess As Process = System.Diagnostics.Process.Start(p)
myProcess.WaitForExit()
myProcess.Close()
End Sub
How can I change a specific control, with variable .text
If Me.Controls.OfType(Of Button) = ("Button" & Bindex) Then
button.Text = PostMyresult
End If
So , no Joy, attached is the code block. Hope its not too polluted:
` Private Sub Button34_Click(sender As Object, e As EventArgs) Handles Button34.Click
Dim DaButton As String
For Bindex As Integer = 1 To 2
DaButton = ("Button" & Bindex & ".Text = SAMPLE" & Bindex)
MessageBox.Show(DaButton)
' Me.Button1.Text = "SAMPLE1"
CollectSample(DaButton & ".Text" & ".txt") 'works grabs sample from spectrum anlzr
CheckSample(DaButton & ".Text" & ".txt") 'works error check
' MessageBox.Show(SampleFlag)
If SampleFlag <> 0 Then
SendMyAvg = Math.Round(SendMyAvg, 2)
If SendMyAvg < 1 Then
MessageBox.Show("Average Sample Is < 1 ")
' Me.Button1.Text = "SAMPLE1"
For Each myCtrl As Control In Me.Controls
If (TypeOf myCtrl Is Button) Then
If myCtrl.Name = "Button" & Bindex Then
myCtrl.Text = DaButton
End If
End If
Next
Exit Sub
End If
' MessageBox.Show("Button" & Bindex & " / " & SendMyAvg)
For Each myCtrl As Control In Me.Controls
If (TypeOf myCtrl Is Label) & myCtrl.Name = "Label" & Bindex Then
myCtrl.Text = SendMyAvg
MessageBox.Show("Button" & Bindex & " / " & SendMyAvg)
End If
Next
' Button1.Text = SendMyAvg
' MsgBox("Avg Is " & SendMyAvg)
End If
Next
End Sub`
Well if you have Linq, you can do this:
Dim btn = Me.Controls.OfType(Of Button).Where(Function(x) x.Name = "Button1" & Bindex)
If btn.Count > 0 Then
btn(0).Text = "New Text"
End If
Try this:
For Each myBtn as Button In Me.Controls.OfType(Of Button)
If myBtn.Name = "Button" & Bindex Then
myBtn.Text = PostMyResult
End If
Next
solution:
DirectCast(Me.Controls.Find("Label" & Bindex, True)(0), Label).Text = SendMyAvg
Try this:
Dim c As Control
Dim myButton As String
For i = 1 To 2
myButton = "Button" & i
c = Controls.Find(myButton, True).FirstOrDefault()
c.Text = "New Text"
Next i