Creating error-checking for multiple textbox fields vb2010 - vb.net-2010

I am new to VB and am attempting to expand on a BASIC256 program we created in class the other night. I successfully created a console version of the app (code below) and windows forms version. I need help creating error checking for the text boxes. For TextBox1 I am looking to prevent a blank field. For TextBox3 I am wanting to require a positive number with no more than 2 decimal places. Also, I know the code is probably overly complicated, any cleaning suggestions would be greatly appreciated.
Console Code
Module Module1
Sub Main()
Dim check_num(10) As String
Dim description(10) As String
Dim amount(10) As Decimal
Dim total_bal(10) As Decimal
Dim pointer As Integer
Dim x As Integer
pointer = 0
start:
Console.Clear()
Console.WriteLine("Enter check number for a check")
Console.WriteLine("Enter B for a balance inquiry")
Console.WriteLine("Enter C for a bank charge")
Console.WriteLine("Enter D for a deposit")
Console.WriteLine("Enter F if you are finished")
Console.WriteLine("Enter choice: ")
check_num(pointer) = Console.ReadLine()
Select Case check_num(pointer)
Case "B", "b"
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
x = x - 1
If x < 0 Then
x = 0
End If
Else
If total_bal(x) <> 0 Then
GoTo cont
End If
End If
Console.WriteLine("Balance is: {0}", total_bal(x))
Console.WriteLine("Press any key to continue...")
Console.ReadKey(True)
GoTo start
cont:
Next x
Case "D", "d"
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
Console.WriteLine("Amount of deposit: ")
amount(x) = Console.ReadLine()
Console.WriteLine("Descripiton of transaction: ")
description(x) = Console.ReadLine()
If x = 0 Then
total_bal(x) = total_bal(x) + amount(x)
Else
total_bal(x) = total_bal(x - 1) + amount(x)
End If
GoTo start
End If
Next x
Case "F", "f"
End
Case Else
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
Console.WriteLine("Amount of debit: ")
amount([x]) = Console.ReadLine()
Console.WriteLine("Descripiton of transaction: ")
description$([x]) = Console.ReadLine()
If x = 0 Then
total_bal(x) = total_bal(x) - amount(x)
Else
total_bal(x) = total_bal(x - 1) - amount(x)
End If
GoTo start
End If
Next x
End Select
GoTo start
End Sub
End Module
Windows Forms Code
Public Class Form1
Dim check_num(10) As String
Dim description(10) As String
Dim amount(10) As Decimal
Dim total_bal(10) As Decimal
Dim pointer As Integer = 0
Dim x As Integer
Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
If RadioButton1.Checked = True Then
Label3.Visible = True
TextBox3.Visible = True
Label2.Visible = True
TextBox1.Visible = True
Button1.Visible = True
End If
End Sub
Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
If RadioButton2.Checked = True Then
Label3.Visible = True
TextBox3.Visible = True
Label2.Visible = True
TextBox1.Visible = True
Button1.Visible = True
End If
End Sub
Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
If RadioButton3.Checked = True Then
Label3.Visible = True
TextBox3.Visible = True
Label2.Visible = True
TextBox1.Visible = True
Button1.Visible = True
End If
End Sub
Private Sub RadioButton4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton4.CheckedChanged
If RadioButton4.Checked = True Then
Label3.Visible = False
TextBox3.Visible = False
Label2.Visible = False
TextBox1.Visible = False
Button1.Visible = False
End If
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
x = x - 1
If x < 0 Then
x = 0
End If
GoTo Line1
End If
Next x
Line1:
Label4.Visible = True
TextBox2.Visible = True
TextBox2.Text = total_bal(x).ToString("n2")
MessageBox.Show("Press OK to clear the screen.")
Label4.Visible = False
TextBox2.Visible = False
RadioButton4.Checked = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
If TextBox3.Text <> String.Empty Then
If Not Decimal.TryParse(TextBox3.Text, amount(x)) Then
MessageBox.Show("Please use 12345.67 format only.")
TextBox3.Focus()
Else
amount(x) = TextBox3.Text
description(x) = TextBox1.Text
GoTo Line1
End If
End If
End If
Next x
Line1:
If x = 0 Then
total_bal(x) = total_bal(x) - amount(x)
Else
total_bal(x) = total_bal(x - 1) - amount(x)
End If
MessageBox.Show("Check Number " & description(x) & " was withdrawn" & vbCrLf & "in the amount of $" & amount(x))
End If
If RadioButton2.Checked = True Then
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
If TextBox3.Text <> String.Empty Then
If Not Decimal.TryParse(TextBox3.Text, amount(x)) Then
MessageBox.Show("Please use 12345.67 format only.")
TextBox3.Focus()
Else
amount(x) = TextBox3.Text
description(x) = TextBox1.Text
GoTo Line2
End If
End If
End If
Next x
Line2:
If x = 0 Then
total_bal(x) = total_bal(x) - amount(x)
Else
total_bal(x) = total_bal(x - 1) - amount(x)
End If
MessageBox.Show("A fee for " & description(x) & " was withdrawn" & vbCrLf & "in the amount of $" & amount(x))
End If
If RadioButton3.Checked = True Then
x = 0
For x = 0 To 10
If total_bal(x) = 0 Then
If TextBox3.Text <> String.Empty Then
If Not Decimal.TryParse(TextBox3.Text, amount(x)) Then
MessageBox.Show("Please use 12345.67 format only.")
TextBox3.Focus()
Else
amount(x) = TextBox3.Text
description(x) = TextBox1.Text
GoTo Line3
End If
End If
End If
Next x
Line3:
If x = 0 Then
total_bal(x) = total_bal(x) + amount(x)
Else
total_bal(x) = total_bal(x - 1) + amount(x)
End If
MessageBox.Show("A deposit for " & description(x) & " was made" & vbCrLf & "in the amount of $" & amount(x))
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Label3.Visible = False
TextBox3.Visible = False
Label2.Visible = False
TextBox1.Visible = False
Button1.Visible = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Response As Integer
Response = MessageBox.Show("Do you really want to exit?", "", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Response = vbYes Then
Me.Close()
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Array.Clear(check_num, 0, check_num.Length)
Array.Clear(description, 0, description.Length)
Array.Clear(amount, 0, amount.Length)
Array.Clear(total_bal, 0, total_bal.Length)
End Sub
End Class

For textbox1, add a check on whatever button you use on that particular text box. The check would be something like this
If textbox1.text = String.Empty (or you can use "") Then
'Throw an error of some sort
End If
For textbox2, add a KeyPress event handler for that text box. It would look something like this
Private Sub textbox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtbox1.KeyPress
Dim iKeyPress as Integer = Asc(e.KeyChar)
Dim hasDecimal as Boolean = False
IF iKeyPress < 48 Or iKeyPress > 57 Then ' Only Allow Numbers
e.Handled = True
End If
Select Case iKeyPress
Case 46 'Decimal
If hasDecimal = False Then
e.Handled = True
hasDecimal = True
End If
End Select
End Sub

Related

Show the next contents in a table in Word

Scenario
I have a word document where I have a table as shown in Image 1. The checkboxes are used to show the next contents. For example, I have in first step yes and no, when yes is checked the next content is shown. And in next step, I have thre Checkboxes with case 1,2 and 3 respectively.
When the case 1 is checked I have next a text that is filled via vba as F1Feld1...till F4Feld1.
Problem
First problem is, I am unable to create a function where only yes and no can be checked as well as either of the case can be checked. Second, problem is that the vba for case checkboxes run perfectly when I have them created separate but when combined together only case 1 vba runs.
Following is my code:
Option Explicit
Dim tabelle As Table, zelle As Cell
Private Sub Document_ContentControlOnEnter(ByVal CC As ContentControl)
Dim r As Range
Set tabelle = ActiveDocument.Bookmarks("local").Range.Tables(1)
If ActiveDocument.SelectContentControlsByTag("Yes").Item(1).Checked = True Then
ActiveDocument.SelectContentControlsByTag("No").Item(1).Checked = False
Call local_blockiert
Else: Call local_offen
End If
If ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = True Then
On Error Resume Next
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F1Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F1Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F1Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F1Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case1").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = True Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F2Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F2Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F2Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F2Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case2").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = True Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = "F3Feld1": .Bookmarks("TB1").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB2").Range.Text = "F3Fed2": .Bookmarks("TB2").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB3").Range.Text = "F3Feld3": .Bookmarks("TB3").Range.Font.ColorIndex = wdBlack
.Bookmarks("TB4").Range.Text = "F3Feld4": .Bookmarks("TB4").Range.Font.ColorIndex = wdBlack
End With
ElseIf ActiveDocument.SelectContentControlsByTag("Case3").Item(1).Checked = False Then
With ActiveDocument
.Bookmarks("TB1").Range.Text = ""
.Bookmarks("TB2").Range.Text = ""
.Bookmarks("TB3").Range.Text = ""
.Bookmarks("TB4").Range.Text = ""
End With
End If
End Sub
Private Sub local_blockiert()
Dim i As Long, j As Long
On Error GoTo fehler
With ActiveDocument.Bookmarks("local").Range
.Font.ColorIndex = wdWhite
End With
fehler:
Call AllesAuf
End Sub
Private Sub local_offen()
Dim i As Long, j As Long
On Error GoTo fehler
With ActiveDocument.Bookmarks("YesorNo").Range
.Font.ColorIndex = wdBlack
End With
fehler:
Call AllesAuf
End Sub
Private Sub yes_blockiert()
Dim j As Long
On Error GoTo fehler
With tabelle.Cell(2, 2)
.Shading.ForegroundPatternColorIndex = wdGray25
.Range.Font.ColorIndex = wdGray25
For j = 1 To .Range.ContentControls.Count
.Range.ContentControls(j).LockContents = True
Next j
End With
Exit Sub
fehler:
Call AllesAuf
End Sub
Private Sub yes_offen()
Dim j As Long
On Error GoTo fehler
With tabelle.Cell(2, 2)
For j = 1 To .Range.ContentControls.Count
.Range.ContentControls(j).LockContents = False
Next j
.Shading.ForegroundPatternColor = RGB(255, 242, 204)
.Range.Font.ColorIndex = wdAuto
End With
Exit Sub
fehler:
Call AllesAuf
End Sub
Private Sub AllesAuf()
Dim i As Long
With ActiveDocument
For i = 1 To .ContentControls.Count
.ContentControls(i).LockContents = False
Next i
End With
End Sub

I'm trying to do a loop for this and this is what I did, but it will not work

I want to make all the labels, checkboxes and comboboxes to Enabled when the combobox item is 0.
For i = 1 To 5
Dim MycbmQty As ComboBox = CType(Me.Controls("cbmQty" & i), ComboBox)
Dim myLabel As Label = CType(Me.Controls("lblSumname" & i), Label)
Dim MybtnSum As Button = CType(Me.Controls("btnSum" & i), Button)
Dim myLabel2 As Label = CType(Me.Controls("lblSumPrice" & i), Label)
Dim myLabel3 As Label = CType(Me.Controls("lblPriceTit" & i), Label)
Dim myLabel4 As Label = CType(Me.Controls("lblQtyTit" & i), Label)
Dim mychkname As CheckBox = CType(Me.Controls("chkName" & i), CheckBox)
If MycbmQty.SelectedIndex = 0 Then
myLabel.Enabled = False
MybtnSum.Enabled = False
myLabel2.Enabled = False
myLabel3.Enabled = False
myLabel4.Enabled = False
mychkname.Checked = False
MycbmQty.Enabled = False
End If
Next
However, it will work if I do this instead.
Private Sub cbmQty1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbmQty1.SelectedIndexChanged
If cbmQty1.SelectedIndex = 0 Then
lblSumName1.Enabled = False
btnSum1.Enabled = False
lblSumPrice1.Enabled = False
lblPriceTit1.Enabled = False
lblQtyTit1.Enabled = False
cbmQty1.Enabled = False
chkName1.Checked = False
End If
End Sub
Private Sub cbmQty2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbmQty2.SelectedIndexChanged
If cbmQty2.SelectedIndex = 0 Then
lblSumName2.Enabled = False
btnSum2.Enabled = False
lblSumPrice2.Enabled = False
lblPriceTit2.Enabled = False
lblQtyTit2.Enabled = False
cbmQty2.Enabled = False
chkName2.Checked = False
End If
End Sub
Private Sub cbmQty3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbmQty3.SelectedIndexChanged
If cbmQty3.SelectedIndex = 0 Then
lblSumName3.Enabled = False
btnSum3.Enabled = False
lblSumPrice3.Enabled = False
lblPriceTit3.Enabled = False
lblQtyTit3.Enabled = False
cbmQty3.Enabled = False
chkName3.Checked = False
End If
End Sub
Private Sub cbmQty4_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbmQty4.SelectedIndexChanged
If cbmQty4.SelectedIndex = 0 Then
lblSumName4.Enabled = False
btnSum4.Enabled = False
lblSumPrice4.Enabled = False
lblPriceTit4.Enabled = False
lblQtyTit4.Enabled = False
cbmQty4.Enabled = False
chkName4.Checked = False
End If
End Sub
Private Sub cbmQty5_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbmQty5.SelectedIndexChanged
If cbmQty5.SelectedIndex = 0 Then
lblSumName5.Enabled = False
btnSum5.Enabled = False
lblSumPrice5.Enabled = False
lblPriceTit5.Enabled = False
lblQtyTit5.Enabled = False
cbmQty5.Enabled = False
chkName5.Checked = False
End If
End Sub
You do not catch the Change event but query the actual state in the loop.
The goal is the AddHandler line.
Sub main
For i = 1 To 5
Dim MycbmQty As ComboBox = CType(Me.Controls("cbmQty" & i), ComboBox)
Dim myLabel As Label = CType(Me.Controls("lblSumname" & i), Label)
Dim MybtnSum As Button = CType(Me.Controls("btnSum" & i), Button)
Dim myLabel2 As Label = CType(Me.Controls("lblSumPrice" & i), Label)
Dim myLabel3 As Label = CType(Me.Controls("lblPriceTit" & i), Label)
Dim myLabel4 As Label = CType(Me.Controls("lblQtyTit" & i), Label)
Dim mychkname As CheckBox = CType(Me.Controls("chkName" & i), CheckBox)
AddHandler MycbmQty.SelectedIndexChanged,
Sub()
If MycbmQty.SelectedIndex = 0 Then
lblSumName2.Enabled = False
btnSum2.Enabled = False
lblSumPrice2.Enabled = False
lblPriceTit2.Enabled = False
lblQtyTit2.Enabled = False
cbmQty2.Enabled = False
chkName2.Checked = False
End If
End Sub
Next
end sub

How to fix InvalidArgument= Value of '3' is not valid for 'index'. Parameter name: index in exporting listview items to excel

I'm setting up a program, and want to save my listview items to Excel, but there's always an error in saving my items.
I;m using Windows 7 and Visual Basic 2010. There are actually 3 columns, and an unexpected number of rows since I'm running a food menu program, so the number of subitems are unexpected.
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button13.Click
Try
Me.Cursor = Cursors.WaitCursor
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For i = 1 To Me.ListView1.Items.Count
.cells(i, 1) = Me.ListView1.Items(i - 1).Text
For j = 1 To ListView1.Columns.Count - 1
.cells(i, j + 1) = Me.ListView1.Items(i - 1).SubItems(j).Text
Next
Next
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
Exit Sub
End Sub
I expect it to display on the Excel program with the following listview items, but there's just an error, so it can't proceed.
Please try the below updated code:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Try
Me.Cursor = Cursors.WaitCursor
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For i = 0 To Me.ListView1.Columns.Count - 1
.cells(1, i + 1) = Me.ListView1.Columns(i).Text
Next
For i = 0 To Me.ListView1.Items.Count - 1
For j = 0 To Me.ListView1.Items(i).SubItems.Count - 1
.cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
Exit Sub
End Sub

How can I check an answer then Load a new one

I am trying to make a quiz that reads from a random file, checks the answer then picks a new question. I am having trouble because when I click the button to check the answer it checks it against the next question instead of the current. I think this has something to do with opening the next question before checking. I am only fairly new to Visual Basic and coding in general so any help will be appreciated.
Here is the code giving me the trouble.(Sorry for the big chunk of Code)
Private Sub btn_next_Click(sender As Object, e As EventArgs) Handles btn_next.Click
ProgressBar1.Increment(1)
'Selects Random Number and Puts it into var_qnum
Dim curNumber As Integer
If (alreadyPicked.Count < var_amount) Then
Dim rand As Random = New Random
Do
curNumber = rand.Next(0, var_amount)
Loop While (alreadyPicked.Contains(curNumber))
End If
If (curNumber >= 0 AndAlso Not alreadyPicked.Contains(curNumber)) Then
alreadyPicked.Add(curNumber)
var_qnum = curNumber
var_filepath = "\questions\" + var_qnum.ToString + ".txt"
Else
End If
'Defines var_row stuff
Dim var_row As Integer = 0
Dim var_question As String
Dim var_type As String
Dim var_answer As String
Dim var_opta As String
Dim var_optb As String
Dim var_optc As String
Dim var_optd As String
'Opens the file corresponding to var_qnum
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
Application.StartupPath & var_filepath)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters("|")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
var_row += 1
If var_row = 1 Then
var_question = currentField
ElseIf var_row = 2 Then
var_type = currentField
ElseIf var_row = 3 Then
var_opta = currentField
ElseIf var_row = 4 Then
var_optb = currentField
ElseIf var_row = 5 Then
var_optc = currentField
ElseIf var_row = 6 Then
var_optd = currentField
ElseIf var_row = 7 Then
var_answer = currentField
var_row = 0
ElseIf var_row = 3 And var_type = "Close" Then
var_answer = currentField
var_row = 0
End If
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"Is Not valid And will be skipped.")
End Try
End While
End Using
lbl_type.Text = var_type
If var_type = "Multiple Choice" Then
rb_a.Visible = True
rb_b.Visible = True
rb_c.Visible = True
rb_d.Visible = True
rb_a.Text = var_opta
rb_b.Text = var_optb
rb_c.Text = var_optc
rb_d.Text = var_optd
End If
lbl_number.Text = var_qnum.ToString
txt_questionbox.Text = var_question
Dim var_check As String = "NULL"
If rb_a.Checked Then
var_check = "a"
ElseIf rb_b.Checked Then
var_check = "b"
ElseIf rb_c.Checked Then
var_check = "c"
ElseIf rb_d.Checked Then
var_check = "d"
End If
If var_check = var_answer Then
var_correct += 1
rb_a.Checked = False
rb_b.Checked = False
rb_c.Checked = False
rb_d.Checked = False
btn_next.Text = "Skip"
var_check = "NULL"
ElseIf var_check = "NULL" Then
var_skip += 1
ElseIf var_check <> var_answer Then
var_incorrect += 1
rb_a.Checked = False
rb_b.Checked = False
rb_c.Checked = False
rb_d.Checked = False
btn_next.Text = "Skip"
var_check = "NULL"
Else
MsgBox("Error")
End If
If var_correct + var_incorrect + var_skip = var_amount Then
Me.Visible = False
Form3.Visible = True
End If
End Sub

Using one datagridview across multiple tabs in tabcontrol

I have a datagridview (datagridview1) on TabPage1 of TabControl1 which is one my 'Records' form. Currently I populate the datagridview with a loop that executes on the page load event and loads the data in from an excel file that it is an included resource. In the loop I also have tabs created and named for each sheet and sheet name that the excel file has. The two sheets I have in the excel file current are name "2012" and "2013". the first tab in the TabControl is named "2013" and the second tab dynamically created and named "2012" because I start the loop by setting the current year sheet to the first tab and the data in the 2013 sheet is read into the datagridview via my loop. What I need help doing is using the same datagridview on each new tab, but updating it to show the respective year's (sheet) data.
Here's my code for Records Form
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Public Class Records
Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim ColumnCount, RowCount, TotalCellCount As Long
Dim yearstamp As String = _
DateTime.Now.ToString("yyyy")
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")
Sub PopulateDataGridView()
'Loop through each column
Dim cIndex As Integer = 0
Dim rIndex As Integer = 0
While cIndex < DataGridView1.ColumnCount
'Loop through and populate each row in column
rIndex = 0
While rIndex < DataGridView1.RowCount
If cIndex = 0 Then
'Set row header titles
DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()
DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
If cIndex > 0 Then
DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
'Set column header title
DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value
'Change last cell (Result) color Red or Green to represent positive gain or negative loss
If rIndex = RowCount - 2 Then
If DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
End If
End If
rIndex = rIndex + 1
End While
'Make column unsortable
DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable
cIndex = cIndex + 1
End While
End Sub
Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Get the Excel application object.
excel_app = New Excel.Application
' Make Excel visible (optional).
excel_app.Visible = False
' Open the workbook.
workbook = excel_app.Workbooks.Open(xlPath)
sheet_name = yearstamp
'Adds tabs (if needed) and names each tab after respective excel file sheet
Dim name As String
For w As Integer = 1 To workbook.Sheets.Count
name = workbook.Sheets(w).name
If Not (TabControl1.TabPages.Count = workbook.Sheets.Count) Then
TabPage1.Text = sheet_name
' Create the new tab page
Dim tab As New TabPage(name)
' Add the tabpage to the existing TabCrontrol
TabControl1.TabPages.Add(tab)
End If
Next w
sheet = excel_app.Worksheets(sheet_name)
ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
RowCount = sheet.Range("A1").CurrentRegion.Rows.Count
DataGridView1.ColumnCount = ColumnCount - 1
DataGridView1.RowCount = RowCount - 1
DataGridView1.ColumnHeadersVisible = True
DataGridView1.RowHeadersVisible = True
TotalCellCount = DataGridView1.ColumnCount * DataGridView1.RowCount
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.AllowUserToResizeRows = False
DataGridView1.ReadOnly = True
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'Calls Loop to populate the datagridview
PopulateDataGridView()
DataGridView1.AutoResizeColumns()
'Resize all Row Headers so user can see Row Titles without resizing
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
End Sub
Private Sub dataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.ColumnIndex > -1 And e.RowIndex > -1 Then
If DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = " $0.00" Then
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor = Color.White
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor = SystemColors.Highlight
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor
End If
End If
End Sub
I'm editing this only to append the solution in case anyone else needs some guidance. The code below allows my datagridview to be carried to whichever tab is active and also updates the datagridview cells to show the data from the corresponding excel sheet's values. I hope this is able to help!
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Public Class Records
Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim ColumnCount, RowCount, TotalCellCount As Long
Dim yearstamp As String = _
DateTime.Now.ToString("yyyy")
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")
Sub PopulateDataGridView()
'Loop through each column
Dim cIndex As Integer = 0
Dim rIndex As Integer = 0
While cIndex < DataGridView1.ColumnCount
'Loop through and populate each row in column
rIndex = 0
While rIndex < DataGridView1.RowCount
If cIndex = 0 Then
'Set row header titles
DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()
DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
If cIndex > 0 Then
DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
'Set column header title
DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value
'Change last cell (Result) color Red or Green to represent positive gain or negative loss
If rIndex = RowCount - 2 Then
If DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
End If
End If
rIndex = rIndex + 1
End While
'Make column unsortable
DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable
cIndex = cIndex + 1
End While
End Sub
Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Get the Excel application object.
excel_app = New Excel.Application
' Make Excel visible (optional).
excel_app.Visible = False
' Open the workbook.
workbook = excel_app.Workbooks.Open(xlPath)
sheet_name = yearstamp
'Adds tabs (if needed) and names each tab after respective excel file sheet
Dim name As String
For w As Integer = 1 To workbook.Sheets.Count
name = workbook.Sheets(w).name
If Not (TabControl1.TabPages.Count = workbook.Sheets.Count) Then
TabPage1.Text = sheet_name
' Create the new tab page
Dim tab As New TabPage(name)
' Add the tabpage to the existing TabCrontrol
TabControl1.TabPages.Add(tab)
End If
Next w
sheet = excel_app.Worksheets(sheet_name)
ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
RowCount = sheet.Range("A1").CurrentRegion.Rows.Count
DataGridView1.ColumnCount = ColumnCount - 1
DataGridView1.RowCount = RowCount - 1
DataGridView1.ColumnHeadersVisible = True
DataGridView1.RowHeadersVisible = True
TotalCellCount = DataGridView1.ColumnCount * DataGridView1.RowCount
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.AllowUserToResizeRows = False
DataGridView1.ReadOnly = True
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'Calls Loop to populate the datagridview
PopulateDataGridView()
DataGridView1.AutoResizeColumns()
'Resize all Row Headers so user can see Row Titles without resizing
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
End Sub
Private Sub dataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.ColumnIndex > -1 And e.RowIndex > -1 Then
If DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = " $0.00" Then
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor = Color.White
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor = SystemColors.Highlight
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor
End If
End If
End Sub
Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
Dim tab As TabPage = Me.TabControl1.SelectedTab
If ((Not tab Is Nothing) AndAlso (Not tab.Controls.Contains(Me.DataGridView1))) Then
tab.Controls.Add(Me.DataGridView1)
End If
sheet_name = TabControl1.SelectedTab.Text
sheet = excel_app.Worksheets(sheet_name)
PopulateDataGridView()
End Sub
You could just move the DataGridView to the selected TabPage:
Private Sub TabControl1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
Dim tab As TabPage = Me.TabControl1.SelectedTab
If ((Not tab Is Nothing) AndAlso (Not tab.Controls.Contains(Me.DataGridView1))) Then
tab.Controls.Add(Me.DataGridView1)
If (Me.isDataLoaded) Then
'TODO: Me.DataGridView1.DataSource = ?
End If
End If
End Sub
Private isDataLoaded As Boolean = False