So at present I am learning VB and I have a project in which I have to display a picture box based on:
Which radio box is checked
and
if a checkbox to make the picture box visible is checked. As someone who values clean, good code this is my code and it horrifies me. My question, is there some way to condense the following using cases or some other construct I don't know in VB.net?
If CheckBox1.Checked = False Then
BooksPictureBox.Visible = False
MusicPictureBox.Visible = False
PeriodicalsPictureBox.Visible = False
CoffeeBarPictureBox.Visible = False
End If
If RadioButton1.Checked And CheckBox1.Checked = True Then
BooksPictureBox.Visible = True
MusicPictureBox.Visible = False
PeriodicalsPictureBox.Visible = False
CoffeeBarPictureBox.Visible = False
End If
If RadioButton2.Checked And CheckBox1.Checked = True Then
BooksPictureBox.Visible = False
MusicPictureBox.Visible = True
PeriodicalsPictureBox.Visible = False
CoffeeBarPictureBox.Visible = False
End If
If RadioButton3.Checked And CheckBox1.Checked = True Then
BooksPictureBox.Visible = False
MusicPictureBox.Visible = False
PeriodicalsPictureBox.Visible = True
CoffeeBarPictureBox.Visible = False
End If
If RadioButton4.Checked And CheckBox1.Checked = True Then
BooksPictureBox.Visible = False
MusicPictureBox.Visible = False
PeriodicalsPictureBox.Visible = False
CoffeeBarPictureBox.Visible = True
End If
Note- all the images stack on one another, and all of them start without being visible.
I would create a SUb that sets all picBoxes to not visible
Private Sub setInvisible
BooksPictureBox.Visible = False
MusicPictureBox.Visible = False
PeriodicalsPictureBox.Visible = False
CoffeeBarPictureBox.Visible = False
End sub
Then another routine
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
setInvisible
if checkbox1.checked = false then exit sub
if radiobutton1.checked = true then bookspicturebox.visible = true
if radiobutton2.checked = true then musicpicturebox.visible = true
etc...
End Sub
Of course, an easier way would be to just have the image dynamically load based upon radio button selection.
Maybe this?
' Set first condition, the check box must be checked
BooksPictureBox.Visible = CheckBox1.Checked
MusicPictureBox.Visible = CheckBox1.Checked
PeriodicalsPictureBox.Visible = CheckBox1.Checked
CoffeeBarPictureBox.Visible = CheckBox1.Checked
' Set individual conditions, the radio button must be checked
BooksPictureBox.Visible = RadioButton1.Checked
MusicPictureBox.Visible = RadioButton2.Checked
PeriodicalsPictureBox.Visible = RadioButton3.Checked
CoffeeBarPictureBox.Visible = RadioButton4.Checked
Edit: Or, you could take a different Clean Code approach :)
ShowOrHidePictureBoxes()
...
Private Sub ShowOrHidePictureBoxes
ShowOrHideBooks()
ShowOrHideMusic()
ShowOrHidePeriodicals()
ShowOrHideCoffeeBar()
End Sub
Private Sub ShowOrHideBooks
BooksPictureBox.Visible = RadioButton1.Checked And CheckBox1.Checked
End Sub
Private Sub ShowOrHideMusic
BooksPictureBox.Visible = RadioButton2.Checked And CheckBox1.Checked
End Sub
Private Sub ShowOrHidePeriodicals
BooksPictureBox.Visible = RadioButton3.Checked And CheckBox1.Checked
End Sub
Private Sub ShowOrHideCoffeeBar
BooksPictureBox.Visible = RadioButton4.Checked And CheckBox1.Checked
End Sub
You could take this further in two ways:
Extract the logic out into a shared helper class to re-use throughout the application, or even into actual models which represent the business concepts in the application. This will depend heavily on how the rest of the application is to be designed, what the business needs are, etc. In the context of this question it's more of a thought exercise than a real answer.
Name your controls better so that the code looks more expressive. Things like CheckBox1 and RadioButton1 pollute the code more than the If statements did :)
You could get it down to something like:
Dim fBooksVisible As Boolean
Dim fMusicVisible As Boolean
Dim fPeriodicalsVisible As Boolean
Dim fCoffeeBarVisible As Boolean
If CheckBox1.Checked Then
fBooksVisible = RadioButton1.Checked
fMusicVisible = RadioButton2.Checked
fPeriodicalsVisible = RadioButton3.Checked
fCoffeeBarVisible = RadioButton4.Checked
End If
BooksPictureBox.Visible = fBooksVisible
MusicPictureBox.Visible = fMusicVisible
PeriodicalsPictureBox.Visible = fPeriodicalsVisible
CoffeeBarPictureBox.Visible = fCoffeeBarVisible
or even:
BooksPictureBox.Visible = RadioButton1.Checked AndAlso CheckBox1.Checked
MusicPictureBox.Visible = RadioButton2.Checked AndAlso CheckBox1.Checked
PeriodicalsPictureBox.Visible = RadioButton3.Checked AndAlso CheckBox1.Checked
CoffeeBarPictureBox.Visible = RadioButton4.Checked AndAlso CheckBox1.Checked
Related
This is the question I'm having difficulty figuring out. I'm unable to get splash screens to show up on my previous two questions I was able to complete the coding and design, but this one is throwing me for a loop.
This is what I have so far
Public Sub New()
InitializeComponent()
label2.Visible = False
label3.Visible = False
label4.Visible = False
comboBox1.Items.Add("Uber")
comboBox1.Items.Add("Subway")
comboBox1.Items.Add("Bus")
End Sub
Private Sub comboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
If comboBox1.SelectedIndex = 0 Then
label2.Visible = True
label3.Visible = True
label4.Visible = True
End If
If comboBox1.SelectedIndex = 1 Then
label2.Visible = True
label3.Visible = True
label4.Visible = False
End If
If comboBox1.SelectedIndex = 2 Then
label2.Visible = True
label3.Visible = True
label4.Visible = False
End If
End Sub
I am done with designing the windows form::
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox2.Visible = False
Label2.Visible = False
ComboBox3.Visible = False
Label3.Visible = False
ComboBox4.Visible = False
Label4.Visible = False
ComboBox5.Visible = False
Label5.Visible = False
DateTimePicker1.Visible = False
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (ComboBox1.Text = "BY-ELECTION") Then
ComboBox2.Visible = True
Label2.Visible = True
DateTimePicker1.Visible = False
ElseIf (ComboBox1.Text = "GENERAL ELECTION") Then
ComboBox2.Visible = False
Label2.Visible = False
ComboBox3.Visible = False
Label3.Visible = False
ComboBox4.Visible = False
Label4.Visible = False
ComboBox5.Visible = False
Label5.Visible = False
DateTimePicker1.Visible = True
End If
End Sub
Private Sub ComboBox4_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox4.SelectedIndexChanged
If ComboBox4.SelectedValue = "" And ComboBox2.Text = "MP" Then
DateTimePicker1.Visible = True
End If
If (ComboBox4.Text = "MVITA") And ComboBox2.Text = "MCA" Then
Label5.Visible = True
ComboBox5.Visible = True
ComboBox5.Items.Clear()
ComboBox5.Items.Add("MAJENGO")
ComboBox5.Items.Add("MAKADARA")
ComboBox5.Items.Add("SHIMANZI")
ComboBox5.Items.Add("TONONOKA")
ComboBox5.Items.Add("TUDOR")
DateTimePicker1.Visible = False
End If
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
If (ComboBox3.Text = "MOMBASA") And ComboBox2.Text = "MP" Or (ComboBox3.Text = "MOMBASA") And ComboBox2.Text = "MCA" Then
Label4.Visible = True
ComboBox4.Visible = True
ComboBox4.Items.Clear()
ComboBox4.Items.Add("CHANGAMWE")
ComboBox4.Items.Add("JOMVU")
ComboBox4.Items.Add("KISAUNI")
ComboBox4.Items.Add("LIKONI")
ComboBox4.Items.Add("MVITA")
ComboBox4.Items.Add("NYALI")
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.Text = "GOVERNORSHIP" Or ComboBox2.Text = "SENATOR" Then
Label3.Visible = True
ComboBox3.Visible = True
Label5.Visible = False
ComboBox5.Visible = False
DateTimePicker1.Visible = True
ComboBox4.Visible = False
Label4.Visible = False
ElseIf ComboBox2.Text = "MP" Or ComboBox2.Text = "MCA" Then
Label3.Visible = True
ComboBox3.Visible = True
DateTimePicker1.Visible = False
Label6.Visible = False
ComboBox4.Visible = False
Label4.Visible = False
ComboBox5.Visible = False
Label5.Visible = False
End If
End Sub
Private Sub ComboBox5_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox5.SelectedIndexChanged
Label6.Visible = True
DateTimePicker1.Visible = True
End Sub
and i am stuck at the command button.
My windows form has 5 combobox with items assigned to them but in this illustration i am going to use one item for example:
Combobox2 has item MCA
Combobox3(labeled COUNTY) has item MOMBASA
Combobox4(labeled CONSTITUENCY) has item MVITA
Combobox5(labeled WARD) has item SHIMANZI
I want if i select item MCA in combobox2 and click the button GENERATE a table:
will be created and saved in the path C:\Users\Administrator\Documents\ and populated in the following format
cell A2 = item selected in combobox3
cell B2= item selected in combobox4
cell C2=item selected in combobox5
cell H2 to be populated with random input be based on gender(male/female) and letters(ABCD only) in that order. ie cell H2= MALE,D
You can refer to the following code to generate DataTable.
Dim dt As DataTable = New DataTable
dt.Columns.Add("COUNTY")
dt.Columns.Add("CONSTITUENCY")
dt.Columns.Add("WARD")
dt.Rows.Add(ComboBox3.SelectedItem.ToString, ComboBox4.SelectedItem.ToString, ComboBox5.SelectedItem.ToString)
Then use the following code to export the data table to Excel:
Dim excelFilePath As String = "excel path"
Dim excelApp = New Excel.Application()
excelApp.Workbooks.Add()
Dim workSheet As Excel._Worksheet = excelApp.ActiveSheet
For i = 0 To dt.Columns.Count - 1
workSheet.Cells(1, i + 1) = dt.Columns(i).ColumnName
Next
For i = 0 To dt.Rows.Count - 1
For j = 0 To dt.Columns.Count - 1
workSheet.Cells(i + 2, j + 1) = dt.Rows(i)(j)
Next
Next
If Not String.IsNullOrEmpty(excelFilePath) Then
Try
workSheet.SaveAs(excelFilePath)
excelApp.Quit()
MessageBox.Show("Excel file saved!")
Catch ex As Exception
Throw New Exception("ExportToExcel: Excel file could not be saved! Check filepath." & vbLf & ex.Message)
End Try
End If
Result of the test looks like:
i have four checkboxes on winform , the user has to select from them on a predefined condition. That is, if the user selecst chkbx1 or chkbx2 or chkbx3 or chkbx4 (any one of them), each selection has a diferrent msg to display.
2nd condition user can select any two chkbx e.g(chk1 +chkbx2,or chkbx1+chkbx3,or chkbx1+chkbx4), each selection hv diferrent msg to display.
3rd condition any three checkbox(chkbx 1+2+3 or 1+3+4,or1+2+4) can be selected. each selection hv diferrent msg to display
4th condition all four hv to select display msg on btnclck.......user hv to select at least one checkbox compulsory
i'm doing it with if else statement
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
MessageBox.Show("U choose 1")
End If
If CheckBox2.Checked = True Then
MessageBox.Show("U choose 2")
If CheckBox3.Checked = True Then
MessageBox.Show("U choose 3")
If CheckBox4.Checked = True Then
MessageBox.Show("U choose 4")
If CheckBox1.Checked = True Then
CheckBox4.Checked = True
MessageBox.Show("U choose 5")
If CheckBox2.Checked = True Then
CheckBox4.Checked = True
MessageBox.Show("U choose 6")
If CheckBox1.Checked = True Then
CheckBox4.Checked = True
CheckBox2.Checked = True
MessageBox.Show("U choose 7")
If CheckBox1.Checked = True Then
CheckBox4.Checked = True
CheckBox3.Checked = True
MessageBox.Show("U choose 8")
If CheckBox3.Checked = True Then
CheckBox4.Checked = True
CheckBox2.Checked = True
MessageBox.Show("U choose 9")
If CheckBox1.Checked = True Then
CheckBox4.Checked = True
CheckBox2.Checked = True
CheckBox3.Checked = True
MessageBox.Show("U choose 10")
ElseIf CheckBox1.Checked = False Then
CheckBox4.Checked = False
CheckBox2.Checked = False
CheckBox3.Checked = False
MessageBox.Show("select any one")
End If
End If
End If
End If
End If
End If
End If
End If
End If
End Sub
End Class
on closing the msgbx another msg displayed and other chkbxss automatically selected
I'll give you some pointers. Are you a CS student? If so, you'll appreciate that my proposition includes some binary calculations. You see, you have 4 checkboxes, which means that you have 4² different possible outcomes. Doing this with embedded If will be awful to work with.
On the other hand, you can calculate the result you're lookinf for at the very point when the user is finished playing with the checkboxes. You could do this anyway you like. Here are 2 ways to achieve this:
Private Sub ShowResult()
Select Case GetCheckboxesTotal()
Case 0
MessageBox.Show("0")
Case 1
MessageBox.Show("1")
Case 2
MessageBox.Show("2")
Case 3
'...
Case 14
MessageBox.Show("14")
Case 15
MessageBox.Show("15")
End Select
End Sub
Private Function GetCheckboxesTotal() As Integer
Dim total As Integer = 0
If CheckBox1.Checked Then total += 1
If CheckBox1.Checked Then total += 2
If CheckBox1.Checked Then total += 4
If CheckBox1.Checked Then total += 8
Return total
End Function
This solution uses the power of binary math! In this answer, each checkbox is a "bit", and the GetCheckboxesTotal() function calculate the exact combinaison your user checked, from no checkboxes (0) to all checkboxes (15). Notice that, as foretold, this makes for 16 distinct possibilities, which you can address in a nice Select Case where every possibility is treated once in a very readable manner.
Now, what if you don't like the mathematical part of this answer? No worries, friend, there's a very, very easy way to deal with this again:
Private Sub ShowResult()
Select Case True
Case Not CheckBox1.Checked AndAlso Not CheckBox2.Checked AndAlso Not CheckBox3.Checked AndAlso Not CheckBox4.Checked
MessageBox.Show("0")
Case CheckBox1.Checked AndAlso Not CheckBox2.Checked AndAlso Not CheckBox3.Checked AndAlso Not CheckBox4.Checked
MessageBox.Show("1")
Case Not CheckBox1.Checked AndAlso CheckBox2.Checked AndAlso Not CheckBox3.Checked AndAlso Not CheckBox4.Checked
MessageBox.Show("2")
Case CheckBox1.Checked AndAlso CheckBox2.Checked AndAlso Not CheckBox3.Checked AndAlso Not CheckBox4.Checked
'...
Case Not CheckBox1.Checked AndAlso CheckBox2.Checked AndAlso CheckBox3.Checked AndAlso CheckBox4.Checked
MessageBox.Show("14")
Case CheckBox1.Checked AndAlso CheckBox2.Checked AndAlso CheckBox3.Checked AndAlso CheckBox4.Checked
MessageBox.Show("15")
End Select
End Sub
This manner of dealing with the 16 possible outcomes may be more readable. In fact, it depend on what your boxes means. First example used a logic similar with the numeric file system permissions, so with some systems it may be easier this way, while if every combinaison you have to show cannot be systematized then you might love the other one better.
Good luck and have fun!
I am making a TicTacToe Program in Vb.net and it is essentially 9 games into one "big" game. So I have 81 buttons I want to disable able the winner is determined. How can I address them all in the shortest amount of code?
Private Sub CheckOverallWinner()
If humangame1 = 1 And humangame2 = 1 And humangame3 = 1 Then
MsgBox("Human Wins")
Button1.Enabled = False
Button2.Enabled = False
Button3.Enabled = False
Button4.Enabled = False
Button5.Enabled = False
Button6.Enabled = False
Button7.Enabled = False
Button8.Enabled = False
Button9.Enabled = False
End If
End Sub
So instead of writing Button_.Enabled = False all the way through 81 is there a shorter way? Thanks!
Dim o As Object
For Each o In Me.Controls
If TypeOf o Is Button Then
o.Enabled = False
End If
Next
Just tried this in VS2008
Another option using Controls.Find(). This will work no matter where the buttons are contained, even if they are in multiple containers:
Private Sub Foo()
SetButtonsState(False)
End Sub
Private Sub SetButtonsState(ByVal state As Boolean)
Dim matches() As Control
For i As Integer = 1 To 81
matches = Me.Controls.Find("Button" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
Dim btn As Button = DirectCast(matches(0), Button)
btn.Enabled = state
End If
Next
End Sub
I basically want a survey document where the user selects a rating such as "always" and "never." They select a rating by hitting a radio button. The ratings are weighted and are averaged into a total score, like a GPA, i.e. always is worth 3, somewhat is worth 2 and each question should be added and then averaged. Below is a section of my code for one question.
How do I take the value at the end after the button is selected and average them for all the questions?
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
If RadioButton1.Checked = True Then
RadioButton3.Checked = False
RadioButton2.Checked = False
RadioButton4.Checked = False
RadioButton5.Checked = False
num1 = 2
End If
End Sub
Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
If RadioButton2.Checked = True Then
RadioButton3.Checked = False
RadioButton1.Checked = False
RadioButton4.Checked = False
RadioButton5.Checked = False
num1 = 3
End If
End Sub
Private Sub RadioButton3_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton3.CheckedChanged
If RadioButton3.Checked = True Then
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton4.Checked = False
RadioButton5.Checked = False
num1 = 1
End If
End Sub
Private Sub RadioButton4_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton4.CheckedChanged
If RadioButton4.Checked = True Then
RadioButton3.Checked = False
RadioButton2.Checked = False
RadioButton1.Checked = False
RadioButton5.Checked = False
num1 = 0
End If
End Sub
Private Sub RadioButton5_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton5.CheckedChanged
If RadioButton5.Checked = True Then
RadioButton3.Checked = False
RadioButton2.Checked = False
RadioButton4.Checked = False
RadioButton1.Checked = False
num1 = 0
End If
End Sub
First of all, you can consolidate all of those RadioButton event handlers into ONE handler. Furthermore, you don't have to "uncheck" the other RadioButtons in the group as this will be done automatically for you. Finally, create a separate method that computes the rating and updates the form, then call that method at the bottom of the handler.
That might look something like this:
Private num1 As Integer
Private Sub set1_CheckedChanged(sender As Object, e As EventArgs) Handles _
RadioButton1.CheckedChanged, RadioButton2.CheckedChanged, RadioButton3.CheckedChanged, _
RadioButton4.CheckedChanged, RadioButton5.CheckedChanged
If RadioButton1.Checked Then
num1 = 2
ElseIf RadioButton2.Checked Then
num1 = 3
ElseIf RadioButton3.Checked Then
num1 = 1
ElseIf RadioButton4.Checked Then
num1 = 0
ElseIf RadioButton5.Checked Then
num1 = 0
End If
UpdateRating()
End Sub
Private Sub UpdateRating()
' ... compute the rating using "num1", "num2", "num3", etc ...
' ... then update the GUI with the new value ...
End Sub
Note that all five RadioButtons are listed after the "Handles" keyword making them all fire the same handler. You can do a similar thing for each group of RadioButtons...just make sure each set of RadioButtons is in its OWN container like a GroupBox or Panel. A RadioButton is mutually exclusive with all other RadioButttons in its own container.
I'm not so sure about your case .. but you can try this
Declare your var that will count all result ..
Dim num1 as Integer
Dim num2 as Integer '--> for other group radiobuttons
Dim num3 as Integer '--> for other group radiobuttons
Dim nTotal as Integer
Dim nAvg as Integer
Do this in each checkchanged
Private Sub RadioButton_CheckedChanged(..) Handles RadioButton1_CheckedChanged, RadioButton2_CheckedChanged, .....
'codes
countit()
End Sub
Sub CountIt()
nTotal = num1 + num2 + num3
nAvg = (num1 + num2 + num3) / 3
End Sub