how to link seat reservation project using vb.net with access database - vb.net

I have a code for seat reservation but i don't know how to link it with access database. I am using buttons as seats so when a seat is selected it hides itself so i want help when the seat is selected the seat number shows in access database .Here is my code :
Public Class Form1
Dim seatnumber As char
Private Sub BTNA1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA1.Click
seatnumber = "A1"
Confirmseat()
End Sub
Private Sub BTNA2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA2.Click
seatnumber = "A2"
confirmseat()
End Sub
Private Sub BTNA3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA3.Click
seatnumber = "A3"
Confirmseat()
End Sub
Private Sub BTNA4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA4.Click
seatnumber = "A4"
Confirmseat()
End Sub
Private Sub BTNA5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA5.Click
seatnumber = "A5"
Confirmseat()
End Sub
Private Sub BTNA6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNA6.Click
seatnumber = "A6"
Confirmseat()
End Sub
Private Sub BTNB7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNB7.Click
seatnumber = "B7"
confirmseat()
End Sub
Private Sub BTNB8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNB8.Click
seatnumber = "B8"
confirmseat()
End Sub
Private Sub BTNB9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNB9.Click
seatnumber = "B9"
confirmseat()
End Sub
Private Sub BTNB10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnb10.Click
seatnumber = "B10"
confirmseat()
End Sub
Private Sub BTNB11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnb11.Click
seatnumber = "B11"
confirmseat()
End Sub
Private Sub BTNB12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnb12.Click
seatnumber = "B12"
confirmseat()
End Sub
Public Sub confirmseat()
Dim intresult As Integer
intresult = MessageBox.Show("you selected" & seatnumber, "CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If intresult = Windows.Forms.DialogResult.No Then
seatnumber = "NO"
Else
Select Case (seatnumber)
Case "A1"
BTNA1.Visible = False
Case "A2"
BTNA2.Visible = False
Case "A3"
BTNA3.Visible = False
Case "A4"
BTNA4.Visible = False
Case "A5"
BTNA5.Visible = False
Case "A6"
BTNA6.Visible = False
Case "B7"
BTNB7.Visible = False
Case "B8"
BTNB8.Visible = False
Case "B9"
BTNB9.Visible = False
Case "B10"
btnb10.Visible = False
Case "B11"
btnb11.Visible = False
Case "B12"
btnb12.Visible = False
End Select
MessageBox.Show("Seat" & seatnumber & "is confirmed", "confirmation")
End If
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim seatavailability As Integer
If seatavailability <> "12" Then
BTNA1.Visible = True
BTNA2.Visible = True
BTNA3.Visible = True
BTNA4.Visible = True
BTNA5.Visible = True
BTNA6.Visible = True
BTNB7.Visible = True
BTNB8.Visible = True
BTNB9.Visible = True
btnb10.Visible = True
btnb11.Visible = True
btnb12.Visible = True
Dim i As Integer
Dim reservedseats(1) As Char
For i = 0 To 12
Select Case (reservedseats(1))
Case "BTNA1"
BTNA1.Visible = False
Case "BTNA2"
BTNA2.Visible = False
Case "BTNA3"
BTNA3.Visible = False
Case "BTNA4"
BTNA4.Visible = False
Case "BTNA5"
BTNA5.Visible = False
Case "BTNA6"
BTNA6.Visible = False
Case "BTNB7"
BTNB7.Visible = False
Case "BTNB8"
BTNB8.Visible = False
Case "BTNB9"
BTNB9.Visible = False
Case "BTNB10"
btnb10.Visible = False
Case "BTNB11"
btnb11.Visible = False
Case "BTNB12"
btnb12.Visible = False
End Select
Next
End If
End Sub
Private Sub btncontinue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncontinue.Click
Me.Close()
End Sub
End Class

Note that you have a LOT of duplicate code. You could simplify your code by writing a single button click handler that forwards the button to ConfirmSeat:
Private Sub ClickHandler(sender As Object, e As EventArgs)
Dim seatNumber = Mid(DirectCast(sender, Button).Name, 4)
ConfirmSeat(seatNumber)
End Sub
and write ConfirmSeat as follows:
Private Sub ConfirmSeat(seatNumber As String)
Dim result As Integer
result = MessageBox.Show("you selected" & seatnumber, "CONFIRM", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If intresult = Windows.Forms.DialogResult.No Then
MessageBox.Show("No seat confirmed")
Exit Sub
End If
Dim btn As Button = Controls("btn" & seatNumber)
btn.Visible = False
MessageBox.Show($"Seat {seatNumber} is confirmed", "confirmation")
End Sub
I'm not quite sure what you are trying to do in the Form1_Load, as none of the Select Case will ever be hit. In any event, the handler could be attached to the Click event of the buttons as follows:
For Each ctrl As Control In Controls
If Not TypeOf ctrl Is Button Then Continue
If ctrl Is btnClick Then Continue
AddHandler DirectCast(ctrl, Button).Click, ClickHandler
Next
With that out of the way, we can talk about reading and writing from / to an Access database in your program, using ADO.NET.
Connections and Execute* methods
At the lowest level, you use a connection string:
Dim connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=" & pathToDatabase
to connect to the database with an OleDbConnection:
Using connection AS New OleDbConnection(connectionString)
connection.Open
' do stuff here
End Using
With an open connection, you can execute commands using an OleDbCommand. You can use commands together with the ExecuteNonQuery method to perform update queries:
Dim cmdDeleteAll As New OleDbCommand("DELETE * FROM Persons", connection)
cmdDeleteAll.ExecuteNonQuery
or together with the ExecuteScalar method, to return a single result:
Dim cmdCount As New OleDbCommand("SELECT COUNT(*) FROM Persons", connection)
Dim count As Integer? = cmdCount.ExecuteScalar
or using the ExecuteReader method, return an OleDbDataReader, to iterate once over a set of results -- forward-only.
Using cmd As New OleDbCommand("SELECT * FROM Persons", connection),
rdr = cmd.ExecuteReader
Do While rdr.Read
MessageBox.Show($"{rdr["FirstName"]} {rdr["LastName"]}")
Loop
End Using
Adapters and DataSets
An OleDbDataReader has access to one record at a tine, from a single result set. If you want to load the data from multiple result sets, or you need to keep all the data in memory, you can use the OleDbDataAdapter to load data into a DataSet from an OleDbConnection object:
Dim ds = new DataSet();
Using connection As New OleDbConnection(connectionString)
Dim sql = "SELECT * FROM Persons"
Dim adapter = new OleDbDataAdapter(sql, connection)
adapter.Fill(ds, "Persons")
End Using
Since a DataSet can contain multiple sets of data, there is a hierarchy of objects for working with the DataSets and its DataTables:
(Source: ADO.NET Architecture)
LINQ against a DataReader
You can also use LINQ and LINQ methods on a data reader, to retrieve a set of objects from a single result set:
Dim persons As List(Of Person)
Using reader = cmd.ExecuteReader()
persons = reader.Cast<DbDataRecord>()
.Select(Function(row) New Person With {
.LastName = row["LastName"])
.FirstName = row["FirstName"]
}).ToList
End Using

Related

How to update an Access DB from a DataGridView in Visual Basic

I am creating an inventory application which runs off of an Access DB in visual studio, using visual basic. I can populate my data grid view just fine, but when I try to add new information into the data grid view, it does not number correctly and it does not append my database.
I have tried binding and updating using the table adapter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Here is my code:
Public Class Form1
Private Sub enterbtn_Click(sender As Object, e As EventArgs) Handles enterbtn.Click
If username.Text = "Tanner" And password.Text = "bmis365" Then
GroupBox1.Visible = False
Else
MsgBox("Incorrect Username or Password, please try again.")
username.Clear()
password.Clear()
username.Focus()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.CurrentCell = Nothing
'This line of code loads data into the 'Database1DataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is where my new info is to be appended into the database, once the button is clicked.
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
'The Following Code is from https://social.msdn.microsoft.com/Forums/vstudio/en-US/36c54726-4f49-4e15-9597-7b201ec13ae7/search-in-datagrid-using-textbox-vbnet-without-data-connectivity?forum=vbgeneral
For Each row As DataGridViewRow In DataGridView2.Rows
For Each cell As DataGridViewCell In row.Cells
If Not IsNothing(cell.Value) Then
If cell.Value.ToString.StartsWith(searchbar.Text, StringComparison.InvariantCultureIgnoreCase) Then
cell.Selected = True
DataGridView2.CurrentCell = DataGridView2.SelectedCells(0)
End If
End If
Next
Next
End Sub
End Class
My output initially has 3 rows(numbered 1, 2, and 3) but any that are added through the application have the numbers -1, -2, -3 and so on. Also, when I close the program and restart it, my original rows (1, 2, and 3) are still there from when I entered them in the DB file, but any that were added through my application are gone.
Here is one way to do an Update, as well as a few other common SQL manipulations/operations.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

VB.net RGB color sensor "Integer is not valid"

I'm trying to make VB.net show the data "colors" from my Arduino,
My serial port working great but I have this massage every-time I press connect & weird data show's up
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string " = " to type 'Integer' is not valid.
Can someone help me in this?
this is my code
Public Class Form1
Private _msg As String
Dim R As String
Dim G As String
Dim B As String
Dim iR As String
Dim iG As String
Dim iB As String
Private indata As String
Dim IsConnected As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each str As String In IO.Ports.SerialPort.GetPortNames()
Ports.Items.Add(str)
Next
If (Ports.Items.Count > 0) Then
Ports.SelectedIndex = 0
End If
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (SerialPort1.IsOpen()) Then
Try
SerialPort1.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (SerialPort1.IsOpen = False) Then
SerialPort1.PortName = Ports.SelectedItem
SerialPort1.Open()
IsConnected = True
Status.Text = "Connected"
Status.BackColor = Color.LightGreen
Button1.Enabled = False
Button2.Enabled = True
End If
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'user chose string
'read data waiting in the buffer
Try
Dim msg As String = SerialPort1.ReadExisting()
indata = indata + msg
'Dim where As Integer = InStr(indata, ControlChars.Lf)
Dim where As Integer = InStr(indata, "R=")
If (indata.Length > where + 18) Then
R = indata.Substring(where + 1, 3)
G = indata.Substring(where + 7, 3)
B = indata.Substring(where + 13, 3)
indata = ""
End If
'display the data to the user
_msg = msg
_msg = _msg.Replace(ControlChars.Cr, "")
: DisplayData(msg)
Catch ex As Exception
End Try
End Sub
#Region "DisplayData"
''' <summary>
''' Method to display the data to and
''' from the port on the screen
''' </summary>
''' <remarks></remarks>
<STAThread()> _
Private Sub DisplayData(ByVal msg As String)
DisplayWindow.BeginInvoke(New EventHandler(AddressOf DoDisplay))
End Sub
#End Region
#Region "DoDisplay"
Private Sub DoDisplay(ByVal sender As Object, ByVal e As EventArgs)
'DisplayWindow.SelectedText = String.Empty
'DisplayWindow.SelectionFont = New Font(_DisplayWindow.SelectionFont, FontStyle.Bold)
'DisplayWindow.SelectionColor = MessageColor(CType(_type, Integer))
DisplayWindow.AppendText(_msg)
DisplayWindow.ScrollToCaret()
End Sub
#End Region
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
RL.Text = R
GL.Text = G
BL.Text = B
iR = CInt(R) * CInt(RM.Text)
iG = CInt(G) * CInt(GM.Text)
iB = CInt(B) * CInt(BM.Text)
RF.Text = iR
GF.Text = iG
BF.Text = iB
Try
Label6.BackColor = Color.FromArgb(CType(iR, Byte), CType(iG, Byte), CType(iB, Byte))
Catch ex As Exception
End Try
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)
System.Diagnostics.Process.Start("http://www.narzan.weebly.com/p-1049.html")
End Sub
Private Sub LinkLabel1_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
picOn.Visible = True
SerialPort1.Open()
SerialPort1.Write("^")
SerialPort1.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
picOn.Visible = False
SerialPort1.Open()
SerialPort1.Write("<")
SerialPort1.Close()
End Sub
Private Sub picOn_Click(sender As Object, e As EventArgs) Handles picOn.Click
End Sub
Private Sub RL_Click(sender As Object, e As EventArgs) Handles RL.Click
End Sub
Private Sub RM_TextChanged(sender As Object, e As EventArgs) Handles RM.TextChanged
End Sub
End Class
My problem was from my Arduino code not from VB.net
the solution is to remove "=" from R,G,B
void printColour(){
Serial.print("R = ");
Serial.println(int(colourArray[0]));
Serial.print("G = ");
Serial.println(int(colourArray[1]));
Serial.print("B = ");
Serial.println(int(colourArray[2]));
//delay(2000);
}
so the code will look like that
void printColour(){
Serial.print("");
Serial.println(int(colourArray[0]));
Serial.print("");
Serial.println(int(colourArray[1]));
Serial.print("");
Serial.println(int(colourArray[2]));
//delay(2000);
}
Thanks everyone, everything work great now

DataSource No Longer Fills Data Calls VB 2010

I am using a DataSource in my form app, and it was working fine for calls made across the board, Fill, Add, Delete, etc... It suddenly stopped working. I get no errors on build, no data is added to any ComboBoxes, and no new Adds work either.
I created a new DataSource from the same database that works fine with the exact same connection. The location of the database never moved, no changes were made to any properties of the DataSource or any of the Adapters assigned to the source, it just stopped working. Here is some screen shots and code of my form.
I tried to do a Code Compare but since there are a bunch of Adapters assigned to the source I can't find any anomalies. What would kill a data connection so that the code still sees the connection, but nothing gets filled?
The following code no longer works, no Fill or Add to DCGDataSet;
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs)
'TODO: This line of code loads data into the 'DCGDataSet1.Main' table. You can move, or remove it, as needed.
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
'comboClear()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As System.EventArgs)
' Add new Job to the database
Dim newJobRow As New DCGDataSetTableAdapters.MainTableAdapter
Dim intInsert As Integer
Dim jobText = txtBoxAddNewJob.Text
intInsert = newJobRow.InsertJob(jobText)
If intInsert = 1 Then
MessageBox.Show("New Job Added")
' Update the comboBox values
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
txtBoxAddNewJob.Text = ""
clearTabOne()
Else
MessageBox.Show("Job Not Added")
End If
End Sub
The following call for a ComboBox works fine, this is the new DataSource;
Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DCGDataSet1.Main' table. You can move, or remove it, as needed.
Me.MainTableAdapter1.Fill(Me.DCGDataSet1.Main)
End Sub
These pics are of the two DS I am working with, the top one is the non-working DS.
Entire .vb of Form1 Code;
Public Class MainForm
Dim strCurrency As String = ""
Dim acceptableKey As Boolean = False
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DCGDataSet1.Main' table. You can move, or remove it, as needed.
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
comboClear()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As System.EventArgs)
' Add new Job to the database
Dim newJobRow As New DCGDataSetTableAdapters.MainTableAdapter
Dim intInsert As Integer
Dim jobText = txtBoxAddNewJob.Text
intInsert = newJobRow.InsertJob(jobText)
If intInsert = 1 Then
MessageBox.Show("New Job Added")
' Update the comboBox values
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
txtBoxAddNewJob.Text = ""
clearTabOne()
Else
MessageBox.Show("Job Not Added")
End If
End Sub
Private Sub TabPage2_Enter(sender As Object, e As System.EventArgs)
Me.ActiveControl = txtBoxAddNewJob
clearTabOne()
End Sub
Public Sub comboClear()
ComboBox1.SelectedIndex = -1
ComboBox2.SelectedIndex = -1
End Sub
Private Sub TabPage1_Enter(sender As Object, e As System.EventArgs)
'comboClear()
ComboBox1.SelectedIndex = -1
'ComboBox1.SelectedText = ""
End Sub
Private Sub TabPage3_Enter(sender As Object, e As System.EventArgs)
'comboClear()
ComboBox2.SelectedIndex = -1
clearTabOne()
End Sub
Private Sub btnDeleteJob_Click(sender As Object, e As System.EventArgs)
Dim delJobID = ComboBox2.SelectedValue
Dim delJobRowAdpt As New DCGDataSetTableAdapters.MainTableAdapter
Dim delJobRow As DCGDataSet.MainRow
Dim intDelete As Integer
delJobRow = DCGDataSet.Main.FindByID(delJobID)
delJobRow.Delete()
intDelete = delJobRowAdpt.Update(DCGDataSet.Main)
If intDelete = 1 Then
MessageBox.Show("Job Deleted")
'comboClear()
clearTabOne()
'ComboBox2.SelectedValue = -1
Me.MainTableAdapter.Fill(Me.DCGDataSet.Main)
Else
MessageBox.Show("Job Failed to Delete")
End If
ComboBox2.SelectedValue = -1
End Sub
Private Sub FillSubCombo(ByVal subJob As String)
Dim selSubRow = DCGDataSet.SubBilling
Dim selSubValue As New DCGDataSetTableAdapters.SubBillingTableAdapter
Me.SubBillingTableAdapter.SubName(Me.DCGDataSet.SubBilling, subJob)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As System.EventArgs)
Dim subJob As String = ComboBox1.Text
If subJob.Length > 1 Then
Label5.Visible = True
ComboBox3.Visible = True
FillSubCombo(subJob)
End If
End Sub
Public Sub clearTabOne()
Label5.Visible = False
ComboBox3.Visible = False
End Sub
Private Sub TabPage4_Enter(sender As Object, e As System.EventArgs)
clearTabOne()
End Sub
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) OrElse (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse e.KeyCode = Keys.Back Then
acceptableKey = True
Else
acceptableKey = False
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
' Check for the flag being set in the KeyDown event.
If acceptableKey = False Then
' Stop the character from being entered into the control since it is non-numerical.
e.Handled = True
Return
Else
If e.KeyChar = Convert.ToChar(Keys.Back) Then
If strCurrency.Length > 0 Then
strCurrency = strCurrency.Substring(0, strCurrency.Length - 1)
End If
Else
strCurrency = strCurrency & e.KeyChar
End If
If strCurrency.Length = 0 Then
TextBox1.Text = ""
ElseIf strCurrency.Length = 1 Then
TextBox1.Text = "0.0" & strCurrency
ElseIf strCurrency.Length = 2 Then
TextBox1.Text = "0." & strCurrency
ElseIf strCurrency.Length > 2 Then
TextBox1.Text = strCurrency.Substring(0, strCurrency.Length - 2) & "." & strCurrency.Substring(strCurrency.Length - 2)
End If
TextBox1.Select(TextBox1.Text.Length, 0)
End If
e.Handled = True
End Sub
Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DCGDataSet1.Main' table. You can move, or remove it, as needed.
Me.MainTableAdapter1.Fill(Me.DCGDataSet1.Main)
End Sub
End Class
Your not-working code is missing the Handles clauses on Form1_Load and btnAddNew_Click. If you don't connect the event handler to the event (using either a Handles clause or an AddHandler statement), the event handler won't be run.

Disable Button until multiple Textboxes got Validated

I have a form with over 10 textboxes and 1 button, I would like to disable the button with a realtime validation until all textboxes filled with a 10 or a 13 length numeric value, my code is the following so far:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
For Each userID As Control In Me.Controls.OfType(Of TextBox)()
AddHandler userID.TextChanged, AddressOf ValidateAllFields
Next userID
End Sub
Private Sub userID_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
Private Function ValidateAllFields()
Dim Validation As Boolean = True
For Each userID As Control In Me.Controls.OfType(Of TextBox)()
Dim e As New System.ComponentModel.CancelEventArgs
e.Cancel = False
Call userID_Validating(userID, e)
If e.Cancel = True Then Validation = False
Next userID
buttonSave.Enabled = Not Me.Controls.OfType(Of TextBox).Any(Function(userID) userID.Text.Length <> 10 AndAlso userID.Text.Length <> 13)
Return Validation
End Function
Private Sub userID_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles _
user00.Validating, _
user01.Validating, _
user02.Validating, _
user03.Validating, _
user04.Validating, _
user05.Validating, _
user06.Validating, _
user07.Validating, _
user07.Validating, _
user08.Validating, _
user09.Validating, _
user10.Validating, _
user11.Validating
If Not IsNumeric(sender.Text) OrElse (sender.Text.Length <> 10) AndAlso (sender.Text.Length <> 13) Then
ErrorProvider1.SetError(sender, "")
ErrorProvider2.SetError(sender, "Please enter a valid User ID.")
e.Cancel = True
Else
ErrorProvider1.SetError(sender, "Valid User ID.")
ErrorProvider2.SetError(sender, "")
End If
End Sub
Thanks to your help it works as I wanted, but can you help me improve/clean it? I'm still studying vb, I'm open to any suggestion. Thanks in advance!
Here you have a code performing the actions you want:
Dim done1, done2, done3 As Boolean
Dim targetLength1 As Integer = 10
Dim targetLength2 As Integer = 13
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
If (IsNumeric(TextBox1.Text)) Then
If (TextBox1.Text.Length = targetLength1 Or TextBox1.Text.Length = targetLength2) Then
done1 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Try
If (IsNumeric(TextBox2.Text)) Then
If (TextBox2.Text.Length = targetLength1 Or TextBox2.Text.Length = targetLength2) Then
done2 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
Try
If (IsNumeric(TextBox3.Text)) Then
If (TextBox3.Text.Length = targetLength1 Or TextBox3.Text.Length = targetLength2) Then
done3 = True
End If
End If
If (done1 And done2 And done3) Then
Button1.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Enabled = False
End Sub
It accounts just for 3 textboxes (TextBox1, TextBox2 and TextBox3) and 1 button (Button1) but you can extend the idea to as many textboxes as you wish. It relies on the TextChanged even of each textbox. When the condition is met (given textbox has a number whose length is 10 or 13), the corresponding flag is set to true (e.g., done1 for TextBox1...). When all the flags are true (all the textboxes contain the expected information), the button is disabled.
I think would better to use TextChanged Event ..
Private Sub TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, ....., TextBox10.TextChanged
Chk4ButtonEnabled()
End Sub
Sub Chk4ButtonEnabled()
Dim s as String
For Each userID As Control In Me.Controls
If userID.GetType Is GetType(TextBox) Then
s = userID.Text
If Not s.Length = 10 OR Not s.Length = 13 Then
ErrorProvider1.SetError(userID, "")
buttonSave.Enabled = False
Else
ErrorProvider1.SetError(userID, "Valid User ID.")
buttonSave.Enabled = True
End If
End If
Next
End Sub

How do I display the highest average of checkbox when multiple checkboxes checked in VB.NET?

Hi I am trying to make a program that has 6 checkboxes and when one is checked a label displays the actors take in average, but if more than one is checked the label will only show the highest average of the checked boxes.
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
SC = ((Val(425488741) + Val(555909803) + Val(868659354) + Val(966435555) + Val(720388023) + Val(617520987)) / 6)
If CheckBox1.Checked = True Then
Label3.Text = "Sean Connery $" & SC
Exit Sub
End If
End Sub
Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged
GL = 513445231
If CheckBox2.Checked = True Then
Label3.Text = "George Lazenby $" & GL
Exit Sub
End If
End Sub
Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox3.CheckedChanged
RM = ((Val(785677477) + (426826774) + (666367656) + (624527272) + (481005579) + (405873493) + (316186616)) / 7)
If CheckBox3.Checked = True Then
Label3.Text = "Roger Moore $" & RM
Exit Sub
End If
End Sub
Private Sub CheckBox4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox4.CheckedChanged
TD = ((Val(362876056) + (271586451)) / 2)
If CheckBox4.Checked = True Then
Label3.Text = "Timothy Dalton $" & TD
Exit Sub
End If
End Sub
Private Sub CheckBox5_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox5.CheckedChanged
PB = ((Val(499954330) + (465588535) + (504705882) + (546490272)) / 4)
If CheckBox5.Checked = True Then
Label3.Text = "Pierce Brosnan $" & PB
Exit Sub
End If
End Sub
Private Sub CheckBox6_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox6.CheckedChanged
DC = ((Val(640803677) + (586090727)) / 2)
If CheckBox6.Checked = True Then
Label3.Text = "Daniel Craig $" & DC
Exit Sub
End If
End Sub
In the future, when asking a question, please do not include all the unnecessary details. If understand your problem correctly, this is one possible simple solution:
Dim incomes = New Integer() {100, 2000, 500}
Dim names = New String() {"John", "Tim", "Allan"}
Private Sub CheckedListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged
Dim maxIncome As Integer = 0
Dim name As String = ""
For i = 0 To incomes.Length - 1
If CheckedListBox1.GetItemChecked(i) And incomes(i) > maxIncome Then
maxIncome = incomes(i)
name = names(i)
End If
Next
Label1.Text = name & " $" & maxIncome
End Sub
For this code to work you need to create a CheckedListBox with 3 items in it's collection. However, this approach might lead to a very bad code once there are many values. In that case you should use a database or at least a structure like:
Structure People
Dim name As String
Dim income As Integer
Dim checkBox As CheckBox
End Structure
Also the is no need to write Exit Sub anywhere in your code, it does nothing.
Details: Saulius is correct in that you should use a database and that you should use a checkedlistbox instead to make it much easier. However, I will just assume you want to use separate checkboxes for whatever reason.
Solution:
Create an Actor Class
Public Class Actor
Property Name As String
Property TotalValue As Double
End Class
In your main form
Public Sub DisplayHighestPaidActor(ByVal actorName As String, ByVal isChecked As Boolean)
If isChecked Then
'Add the Actor
selectedActors.Add((From actor In allActors
Where actor.Name = actorName).FirstOrDefault())
'Order the Actors
selectedActors = (From actor In selectedActors
Order By actor.TotalValue Descending).ToList()
Else
'Remove the Actor
selectedActors.Remove((From actor In allActors
Where actor.Name = actorName).FirstOrDefault())
'Order the Actors
selectedActors = (From actor In selectedActors
Order By actor.TotalValue Descending).ToList()
End If
If (selectedActors.Count > 0) Then
'Display the highest value
lblHighestPaidActor.Text = selectedActors.Item(0).Name.ToString() _
+ " $" + selectedActors.Item(0).TotalValue.ToString()
Else
lblHighestPaidActor.Text = ""
End If
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
DisplayHighestPaidActor("Sean Connery", CheckBox1.Checked)
End Sub
Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged
DisplayHighestPaidActor("George Lazenby", CheckBox2.Checked)
End Sub
Private Sub CheckBox3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox3.CheckedChanged
DisplayHighestPaidActor("Roger Moore", CheckBox3.Checked)
End Sub