How to randomly change the picture of several picturebox - vb.net

I basically want to know how I can optimize this code. I was trying to create somehow a program that could change the photo of a picturebox, but with a randomizer. Basically, each photo would have its percentage of chance to appear in the picturebox, and after several attempts, the only thing that worked for me was this ugly and badly optimized code, but if I try to fix it, the program simply fails. Well, my code generates a random number from 1 to 100 and depending on the number that is generated, one of the six photos is chosen. It is working, however it changes the image from just one picturebox, and I have over 50 that I want to switch (still random). I put it to change everything in a single button, it took me an hour to do this, and I saw that the program gets very slow so it's out of the question. Is there any way to change them all at once using only one code, but keeping random all 50 pictureboxes?
The idea is that at the end of the 50 picturebox are randomly filled with photos, with pictures that can be repeated, but some are less likely to appear than others.
I know, it was a bit confusing, but even if someone can help me, thank you right away.
My code:
randomvalue = random.Next(1, 101)
If randomvalue = "1" Or randomvalue = "2" Or randomvalue = "3" Or randomvalue = "4" Or randomvalue = "5" Or randomvalue = "6" Or randomvalue = "7" Or randomvalue = "8" Or randomvalue = "9" Or randomvalue = "10" Or randomvalue = "11" Or randomvalue = "12" Or randomvalue = "13" Or randomvalue = "14" Or randomvalue = "15" Or randomvalue = "16" Or randomvalue = "17" Or randomvalue = "18" Or randomvalue = "19" Or randomvalue = "20" Or randomvalue = "21" Or randomvalue = "22" Or randomvalue = "23" Or randomvalue = "24" Or randomvalue = "25" Or randomvalue = "26" Or randomvalue = "27" Or randomvalue = "28" Or randomvalue = "29" Or randomvalue = "30" Or randomvalue = "31" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img1.png")
End If
If randomvalue = "32" Or randomvalue = "33" Or randomvalue = "34" Or randomvalue = "35" Or randomvalue = "37" Or randomvalue = "38" Or randomvalue = "39" Or randomvalue = "40" Or randomvalue = "41" Or randomvalue = "42" Or randomvalue = "43" Or randomvalue = "44" Or randomvalue = "45" Or randomvalue = "46" Or randomvalue = "47" Or randomvalue = "48" Or randomvalue = "49" Or randomvalue = "50" Or randomvalue = "51" Or randomvalue = "52" Or randomvalue = "53" Or randomvalue = "54" Or randomvalue = "55" Or randomvalue = "56" Or randomvalue = "57" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img2.png")
End If
If randomvalue = "58" Or randomvalue = "59" Or randomvalue = "60" Or "61" Or randomvalue = "62" Or randomvalue = "63" Or randomvalue = "64" Or randomvalue = "65" Or randomvalue = "66" Or randomvalue = "67" Or randomvalue = "68" Or randomvalue = "69" Or randomvalue = "70" Or randomvalue = "71" Or randomvalue = "72" Or randomvalue = "73" Or randomvalue = "74" Or randomvalue = "75" Or randomvalue = "76" Or randomvalue = "77" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img3.png")
End If
If randomvalue = "78" Or randomvalue = "79" Or "80" Or randomvalue = "81" Or randomvalue = "82" Or randomvalue = "83" Or randomvalue = "84" Or randomvalue = "85" Or randomvalue = "86" Or randomvalue = "87" Or randomvalue = "88" Or randomvalue = "89" Or randomvalue = "90" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img4.png")
End If
If randomvalue = "91" Or randomvalue = "92" Or randomvalue = "93" Or randomvalue = "94" Or randomvalue = "95" Or randomvalue = "96" Or randomvalue = "97" Or randomvalue = "98" Or randomvalue = "99" Or randomvalue = "100" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img5.png")
End If
If randomvalue = "36" Then
btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img6.png")
End If

I don't know what the actual numbers are because I couldn't be bothered counting but lets' say that your six images should have 10%, 20%, 10%, 20%, 10% and 30% chances of being used respectively. You can use a Select Case to easily filter a random number, e.g.
Select Case myRandom.Next(0, 100)
Case Is < 10 '0-9
'Use first image
Case Is < 30 '10-29
'Use second image
Case Is < 40 '30-39
'Use third image
Case Is < 60 '40-59
'Use fourth image
Case Is < 70 '60-69
'Use fifth image
Case Else '70-99
'Use sixth image
End Select
It's also worth noting that the Random class is inheritable so you can actually create your own class that allows you to specify weightings to the outcomes. I have actually created a WeightedRandom class before but seem not to have kept it anywhere. I think that I'll have to do that again and put it somewhere publicly accessible.
EDIT: Here's a more complete example:
Imports System.IO
Public Class Form1
Private folderPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "imgsx")
Private fileNames As String() = {"img1.png", "img2.png", "img3.png", "img4.png", "img5.png", "img6.png"}
Private imagesByFileName As New Dictionary(Of String, Image)
Private rng As New Random
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Create one Image object per file.
For Each fileName In fileNames
Dim filePath = Path.Combine(folderPath, fileName)
Dim img = Image.FromFile(filePath)
imagesByFileName.Add(fileName, img)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Display a random image in each PictureBox on the form.
For Each pictureBox In Controls.OfType(Of PictureBox)
pictureBox.Image = GetWeightedRandomImage()
Next
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
'Clean up the Images to release the files.
For Each fileName In fileNames
imagesByFileName(fileName).Dispose()
Next
End Sub
Private Function GetWeightedRandomImage() As Image
Dim fileNameIndex As Integer
Select Case rng.Next(0, 100)
Case Is < 10 '0-9
fileNameIndex = 0
Case Is < 30 '10-29
fileNameIndex = 1
Case Is < 40 '30-39
fileNameIndex = 2
Case Is < 60 '40-59
fileNameIndex = 3
Case Is < 70 '60-69
fileNameIndex = 4
Case Else '70-99
fileNameIndex = 5
End Select
Return imagesByFileName(fileNames(fileNameIndex))
End Function
End Class

Related

MS Access 2016 VBA Error "Invalid Operation" It is showing the error with the First IF statement in the second CASE

Option Compare Database
Option Explicit
Public Function Day1DU(InvFullBP As Single) As Single
Dim Current_Frm As Form
Set Current_Frm = Screen.ActiveForm
Dim CalcDuAdjs As Double, HBCO As Double, HBP As Double, AMRF As Double
Only my second time posting so please be nice.
I need to see if there is a value in the field FundDate of the SoldInfo_Tbl. If the field is blank then we need to assume 9/1/2020. If it is not null the it needs to be greater than 8/31/2020 to run the code.
I have never looked for a value this way. I have always referred to the current form.
Having issues with DAO.Database
ADVERSE MARKET REFINANCE FEE
Dim dbMyDB As DAO.Database
Dim tblSoldInfo As DAO.TableDef
Dim fldMyField As DAO.Field
Dim rs As DAO.Recordset
Set dbMyDB = CurrentDb
Set tblSoldInfo = dbMyDB![SoldInfo_Tbl]
Set fldMyField = tblSoldInfo![FundDate]
Set rs = CurrentDb.OpenRecordset("SoldInfo_Tbl", dbOpenTable)
ADVERSE MARKET REFINANCE FEE
Select Case Val(Current_Frm!InvestorID_Cbo.Column(0))
Case 2, 4, 15
If Current_Frm!RateSheetDate_Txt > #8/12/2020# Then
If Current_Frm!LoanType_Cbo <> "PURCHASE" And (Current_Frm!Plan_Cbo = "10" Or Current_Frm!Plan_Cbo = "20" Or Current_Frm!Plan_Cbo = "11" Or Current_Frm!Plan_Cbo = "55" Or Current_Frm!Plan_Cbo = "71" Or Current_Frm!Plan_Cbo = "101" Or Current_Frm!Plan_Cbo = "12" Or Current_Frm!Plan_Cbo = "10H" Or Current_Frm!Plan_Cbo = "20H" Or Current_Frm!Plan_Cbo = "55H" Or Current_Frm!Plan_Cbo = "71H" Or Current_Frm!Plan_Cbo = "101H" Or Current_Frm!Plan_Cbo = "11H" Or Current_Frm!Plan_Cbo = "12H") Then
AMRF = 0.5
Else
AMRF = 0
End If
End If
Case 16, 17
My issue below vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
If Nz(rs![tblSoldInfo]![fldMyField], #9/1/2020#) > #8/31/2020# Then
If Current_Frm!LoanType_Cbo <> "PURCHASE" And (Current_Frm!Plan_Cbo = "10" Or Current_Frm!Plan_Cbo = "20" Or Current_Frm!Plan_Cbo = "11" Or Current_Frm!Plan_Cbo = "12" Or Current_Frm!Plan_Cbo = "10H" Or Current_Frm!Plan_Cbo = "20H" Or Current_Frm!Plan_Cbo = "11H" Or Current_Frm!Plan_Cbo = "12H") Then
AMRF = 0.5
Else
AMRF = 0
End If
End If
End Select
END ADVERSE MARKET refinance FEE
I finally figured it out. I have a split ms-access database. If the database is split the tables are not local and I can't use OpenRecordset("SoldInfo_Tbl", dbOpenTable), I have to use dbOpenDynaset.

Random letter and value Powerpoint VBA

I'm trying to obtain a random generated output with this kind of options:
Firstly a letter which could be R or L
Secondly a number that could only be 15, 30, 45 or 60.
For example an output could be R45 or L15.
All this should be generated randomly every time the slide is opened.
I tried with this code but without results, no output appears in the label. Can someone give me a hint?
signA = "R"
signB = "L"
cont = Int(Rnd * 100) + 1
Angle = Int(Rnd * 120) + 1
valore = cont Mod 2
If valore = 0 Then
If Angle <= 30 Then
vardec = "15"
var = signA & vardec
Else
If Angle <= 60 Then
vardec = "30"
var = signA & vardec
Else
If Angle <= 90 Then
vardec = "45"
var = signA & vardec
Else
vardec = "60"
var = signA & vardec
End If
End If
End If
Else
If Angle <= 30 Then
vardec = "15"
var = signA & vardec
Else
If Angle <= 60 Then
vardec = "30"
var = signA & vardec
Else
If Angle <= 90 Then
vardec = "45"
var = signA & vardec
Else
vardec = "60"
var = signA & vardec
End If
End If
End If
End If
ActivePresentation.Slides(4).Shapes("Label2").OLEFormat.Object.Caption = CStr(var)
The instructions actually work, i tested it on a text label, just check you're referencing the label correctly.

vb.NET - Transferred my console application code to windows forms and I need some tweaks to display the result

I have coded a few programs in console applications for my college projects but now I need to use windows forms to display my results properly. I transferred my console code over, took out the console.writeline(s) and console.readline(s), instead I saved the input from a textbox using:
Dim SoundexString As String = StringInput.Text
Anyway, my code outputted fine in console and I have managed to get other things to output in windows forms using 'messagebox.show(xxx) and 'textbox.text = xxx'. For some reason my current code just won't output the final variable "SoundexCode"... I would be grateful for any advice. Code Below:
Public Class Form1
Public Sub ButtonConvert_Click(sender As Object, e As EventArgs) Handles ButtonConvert.Click
Dim SoundexString As String = StringInput.Text
Dim SoundexCode(5) As Char
For i = 1 To 5
SoundexCode(i) = "0"
Next
GetSoundex(SoundexString, SoundexCode)
MessageBox.Show(SoundexCode)
End Sub
Function GetSoundex(ByVal SoundexString As String, ByRef SoundexCode() As Char)
Dim StringLength As Integer = Len(SoundexString)
Dim LetterArray(StringLength) As Char
'Soundex arrays to check each rule before creating soundex code
Dim SoundexNumbers(StringLength) As Char
Dim DoubleLetters(StringLength) As Char
Dim ConsonantVowel(StringLength) As Char
'Assigning Number Locations to Individual Letters, Each Letter is in Correct Position
For i = 1 To StringLength
LetterArray(i) = CChar(SoundexString(i - 1))
Next
'1. Soundex Letters into Numbers
GetSoundexNumbers(LetterArray, SoundexNumbers, StringLength)
'2. Names with Double Letters / Double Soundex Numbers
RemoveDuplicateLetters(LetterArray, DoubleLetters, StringLength, SoundexNumbers)
'3. Consonant Vowel Seperation
SeperateConsonantVowel(LetterArray, StringLength, SoundexNumbers, ConsonantVowel)
'4. Creating Soundex
GetSoundexCode(LetterArray, StringLength, SoundexNumbers, DoubleLetters, ConsonantVowel, SoundexCode)
Return SoundexCode
End Function
Function GetSoundexNumbers(ByVal LetterArray() As Char, ByRef SoundexNumbers() As Char, ByVal StringLength As Integer)
For i = 1 To StringLength
SoundexNumbers(i) = LetterArray(i)
Next
For i = 1 To StringLength
Select Case SoundexNumbers(i)
Case "b", "f", "p", "v", "B", "F", "P", "V"
SoundexNumbers(i) = "1"
Case "c", "g", "j", "k", "q", "s", "x", "z", "C", "G", "J", "K", "Q", "S", "X", "Z"
SoundexNumbers(i) = "2"
Case "d", "t", "D", "T"
SoundexNumbers(i) = "3"
Case "l", "L"
SoundexNumbers(i) = "4"
Case "m", "M", "n", "N"
SoundexNumbers(i) = "5"
Case "r", "R"
SoundexNumbers(i) = "6"
'Unwanted Cases - Vowels / Phonetic Vowels
Case "a", "e", "i", "o", "u", "h", "w", "y", "A", "E", "I", "O", "U", "H", "W", "Y"
SoundexNumbers(i) = "!"
End Select
Next
Return SoundexNumbers
End Function
Function RemoveDuplicateLetters(ByVal LetterArray() As Char, ByRef DoubleLetters() As Char, ByVal StringLength As Integer, ByVal SoundexNumbers() As Char)
For i = 1 To StringLength
DoubleLetters(i) = LetterArray(i)
Next
'Checking Double Letters
For i = 1 To StringLength
If i < StringLength Then
If DoubleLetters(i) = DoubleLetters(i + 1) Then
DoubleLetters(i + 1) = "!"
End If
End If
Next
'Checking Double Soundex Numbers
For i = 1 To StringLength
If i < StringLength Then
If SoundexNumbers(i) = SoundexNumbers(i + 1) Then
DoubleLetters(i + 1) = "!"
End If
End If
Next
Return DoubleLetters
End Function
Function SeperateConsonantVowel(ByVal LetterArray() As Char, ByVal StringLength As Integer, ByVal SoundexNumbers() As Char, ByRef ConsonantVowel() As Char)
For i = 1 To StringLength
ConsonantVowel(i) = LetterArray(i)
Next
'Checking that a Vowel does not have Letters both Sides which Share same Soundex Number
For i = 1 To StringLength
If i > 1 And i < StringLength Then
If ConsonantVowel(i) = "a" Or ConsonantVowel(i) = "e" Or ConsonantVowel(i) = "i" Or ConsonantVowel(i) = "o" Or ConsonantVowel(i) = "u" Or ConsonantVowel(i) = "A" Or ConsonantVowel(i) = "E" Or ConsonantVowel(i) = "I" Or ConsonantVowel(i) = "O" Or ConsonantVowel(i) = "U" Then
If SoundexNumbers(i - 1) = SoundexNumbers(i + 1) Then
ConsonantVowel(i - 1) = "!"
End If
End If
End If
Next
Return ConsonantVowel
End Function
Function GetSoundexCode(ByVal LetterArray() As Char, ByVal StringLength As Integer, ByVal SoundexNumbers() As Char, ByVal DoubleLetters() As Char, ByVal ConsonantVowel() As Char, ByRef SoundexCode() As Char)
SoundexCode(1) = LetterArray(1)
SoundexCode(2) = "-"
Dim Counter As Integer
Dim CounterStore As Integer
For Counter = 2 To StringLength
If SoundexNumbers(Counter) <> "!" And DoubleLetters(Counter) <> "!" And ConsonantVowel(Counter) <> "!" Then
SoundexCode(3) = SoundexNumbers(Counter)
CounterStore = Counter
Exit For
End If
Next
If CounterStore < StringLength Then
For Counter = CounterStore + 1 To StringLength
If SoundexNumbers(Counter) <> "!" And DoubleLetters(Counter) <> "!" And ConsonantVowel(Counter) <> "!" Then
SoundexCode(4) = SoundexNumbers(Counter)
CounterStore = Counter
Exit For
End If
Next
ElseIf CounterStore = StringLength Then
SoundexCode(4) = "0"
SoundexCode(5) = "0"
End If
If CounterStore < StringLength Then
For Counter = CounterStore + 1 To StringLength
If SoundexNumbers(Counter) <> "!" And DoubleLetters(Counter) <> "!" And ConsonantVowel(Counter) <> "!" Then
SoundexCode(5) = SoundexNumbers(Counter)
CounterStore = Counter
Exit For
End If
Next
ElseIf CounterStore = StringLength Then
SoundexCode(5) = "0"
End If
Return SoundexCode
End Function
End Class
Strings are 0-based arrays (first letter starts at index 0) but SoundexCode is a 1-based array (ie. index 0 is null) so when it's converted to a string, SoundexCode appears as an empty string.
To fix your code, just use the String(value As Char(), startIndex As Integer, length As Integer) constructor instead of the regular one.
ie.
MessageBox.Show(New String(SoundexCode, 1, 5))

How to check whether value of a given field is mon negative (greater than zero) in vb.net

The Condition ( less than zero ) is not working in the below code :
Protected Sub txt_business_revenue_risk_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_business_revenue_risk.TextChanged
Dim a As double= 0.0
If IsNumeric(Me.txt_business_revenue_risk.Text) Then
Me.lbl_business_revenue_risk.Text = ""
Me.lbl_rest_risk.Text = CDbl(Me.txt_business_revenue_risk.Text) - CDbl(Me.txt_mitigated_risk.Text)
If CDbl(Me.txt_business_revenue_risk.Text) < CDbl(a) Then
Me.lbl_business_revenue_risk.Text = "Must be a number greater than zero!"
txt_business_revenue_risk.Text = ""
End If
If CDbl(Me.txt_business_revenue_risk.Text) < CDbl(Me.txt_mitigated_risk.Text) Then
Me.lbl_rest_risk.Text = 0
Else
Me.lbl_rest_risk.Text = CDbl(Me.txt_business_revenue_risk.Text) - CDbl(Me.txt_mitigated_risk.Text)
End If
Else
Me.lbl_business_revenue_risk.Text = "Must be a number!"
txt_business_revenue_risk.Text = ""
End If
End Sub
Avoid the usage of VB6 methods such as IsNumeric, and those lot of Double-parsings, try this:
Private Sub txt_business_revenue_risk_TextChanged(sender As Object, e As EventArgs) _
Handles txt_business_revenue_risk.TextChanged
Dim Zero As Double = 0.0
Dim Num1 As Double, Num2 As Double
If Double.TryParse(CStr(sender.text), Num1) _
AndAlso Double.TryParse(CStr(txt_mitigated_risk.Text), Num2) Then
Me.lbl_business_revenue_risk.Text = String.Empty
Me.lbl_rest_risk.Text = CStr(Num1 - Num2)
Select Case Num1
Case Is < Zero
Me.lbl_business_revenue_risk.Text = "Must be a number greater than zero!"
sender.Text = String.Empty
Case Is < Num2
Me.lbl_rest_risk.Text = CStr(Zero)
Case Else
Me.lbl_rest_risk.Text = CStr(Num1 - Num2)
End Select
Else
Me.lbl_business_revenue_risk.Text = "Must be a number!"
txt_business_revenue_risk.Text = String.Empty
End If
End Sub
Try this -- Don't forget to add exception handling
Dim resMsg As String = ""
Dim txtRevRisk As String = Me.txt_business_revenue_risk.Text
Dim txtMitRisk As String = Me.txt_mitigated_risk.Text
Dim dRes As Double = 0
Dim a As Double = 0.0
If IsNumeric(txtRevRisk) AndAlso IsNumeric(txtMitRisk) Then
Dim dRevRisk = CDbl(txtRevRisk)
Dim dMitRisk = CDbl(txtMitRisk)
resMsg = txtRevRisk
dRes = dRevRisk - dMitRisk
If dRevRisk < a Then
resMsg = "Must be a number greater than zero!"
txtRevRisk = ""
End If
If dRevRisk < dMitRisk Then
dRes = 0
'Else
' Me.lbl_rest_risk.Text = dRevRisk - dMitRisk
End If
Else
resMsg = "Must be a number!"
txtRevRisk = ""
End If
Me.lbl_rest_risk.Text = dRes.ToString()
Me.lbl_business_revenue_risk.Text = resMsg.ToString()
Me.txt_business_revenue_risk.Text = txtRevRisk.ToString()

Vb.net register a CTRL-combo with an asyncstate function

I am trying to make a calculator that is fully-controlled with the keypad.
I had some trouble with getting the keystrokes on the keypad registered but eventualy I used a GetAsyncKeystate function
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
For i = 1 To 255
result = 0
result = GetAsyncKeyState(i)
If result = -32767 Then
Select Case i
Case Is = 96
Display.Text = Display.Text & "0"
ans = ans & "0"
Case Is = 97
Display.Text = Display.Text & "1"
ans = ans & "1"
Case Is = 98
Display.Text = Display.Text & "2"
ans = ans & "2"
Case Is = 99
Display.Text = Display.Text & "3"
ans = ans & "3"
Case Is = 100
Display.Text = Display.Text & "4"
ans = ans & "4"
Case Is = 101
Display.Text = Display.Text & "5"
ans = ans & "5"
Case Is = 102
Display.Text = Display.Text & "6"
ans = ans & "6"
Case Is = 103
Display.Text = Display.Text & "7"
ans = ans & "7"
Case Is = 104
Display.Text = Display.Text & "8"
ans = ans & "8"
Case Is = 105
Display.Text = Display.Text & "9"
ans = ans & "9"
Case Is = 106
Multiply()
Case Is = 107
Add()
Case Is = 110
Display.Text = Display.Text & ","
ans = ans & ","
Case Is = 109
Substract()
Case Is = 111
Devide()
Case Is = 13 And ActionValue <> ""
Action()
Display.Text = ans2
Display.Text = Display.Text & Environment.NewLine
ans = ans2
ans2 = ""
End Select
End If
Next i
End Sub
Now I don't know how I should register a Ctrl-combo (like Ctrl + NUM-LOCK)
Btw I'm not used to the GetsAsyncKeyState function
You first need to check if the CTRL-Key or any other modifier-key like Alt or whatever is pressed at the beginning. (refer to http://msdn.microsoft.com/en-us/library/dd375731%28VS.85%29.aspx for the keycodes). Define variables like
Dim isCTRLPressed as Boolean = (GetAsyncKeyState(&HA2) < 0)
When processing the actual keys you can then fork the respective action
If isCTRLPressed Then
DoThis()
Else
DoThat()
End If
If you meant something else you might elaborate on your post some more. Your code is also rather inefficient since you forcefully check every keystate on every Tick wether it is actually used or not.