having a problem in autosearch of textbox in vb.net - vb.net

Iam using autosearch in textbox from database its working good its searching and all the places also changing with the change in that box but problem is that i have a auto generate id box if my autosearch textbox founds nothing then the auto id box should come to its defahult value
Private Sub txtvendorname_frmvdt_TextChanged(sender As Object, e As EventArgs) Handles txtvendorname_frmvdt.TextChanged
Try
conn95.Open()
qryvi = "select * from tblvendorinfo where Vendorname='" & txtvendorname_frmvdt.Text & "'"
cmdcu = New SqlCommand(qryvi, conn95)
cmdcu.ExecuteNonQuery()
drvi = cmdcu.ExecuteReader
If drvi.Read Then
txtvendorid_frmvdt.Text = drvi("Vendorid")
txtvendoraddress_frmvdt.Text = drvi("Vendoraddress")
txtvendorstate_frmvdt.Text = drvi("Vendorstate")
txtvendorgst_frmvdt.Text = drvi("Vendorgstno")
Else
'txtvendorid_frmvdt.Text = drvi("Vendorid")
txtvendoraddress_frmvdt.Text = ""
txtvendorstate_frmvdt.Text = ""
txtvendorgst_frmvdt.Text = ""
End If
conn95.Close()
Loadvendorid1()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Related

Issue with combobox autocomplete in vb.net

I have a combobox populated by a datatable, the code searches for a text string located at any position of the field while the user is writing, so far no problem.
So the problem is: When I write the third character the combobox autocompletes with the first result, and there is no way to type anything else.
I have tried already using all AutocompleteMode & AutocompleteSourse properties settings and combinations.
That’s why I’m asking for help.
The code is below:
Private Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.DroppedDown = True
Cursor.Current = Cursors.Default
End If
End Sub
Thanks
Finally I got something that works well, it is not the final version, surely can be further improved, here is the code:
Public Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If ComboListadoRemitente.Text = "" Then
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.DroppedDown = False
End If
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
If ComboListadoRemitente.Items.Count <> 0 Then
ComboListadoRemitente.DroppedDown = True
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
Cursor.Current = Cursors.Default
Else
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
ComboListadoRemitente.DroppedDown = False
End If
End If
End Sub

data still saving on zero

in my code the data is saving if no.of days to complete=0.I want it should not happen
in my code a msg comes "time to complete and time to acknowledged can be only be posiitve" but still data saves.i dont want it to be saved !!
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
Dim i As Integer
If gvBanckmark.Rows.Count > 0 Then
For i = 0 To gvBanckmark.Rows.Count - 1
Dim lblBenchMarkID As Label = CType(gvBanckmark.Rows(i).FindControl("lblBenchMarkID"), Label)
Dim lblSubCategoryId As Label = CType(gvBanckmark.Rows(i).FindControl("lblSubCategoryId"), Label)
Dim ddlFrequencyTypeAcknowledge As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeAcknowledge"), DropDownList)
Dim ddlFrequencyTypeComplete As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeComplete"), DropDownList)
Dim txtTimeToAcknowledge As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToAcknowledge"), TextBox)
Dim txtTimeToComplete As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToComplete"), TextBox)
Dim objBenchMark As BO.BenchMark = New BO.BenchMark()
objBenchMark.BuildingID = Convert.ToInt32(ddlBuilding.SelectedValue)
objBenchMark.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue)
objBenchMark.SubCategoryID = Convert.ToInt32(lblSubCategoryId.Text.ToString())
objBenchMark.FrequencyTypeToAcknowledge = ddlFrequencyTypeAcknowledge.SelectedValue.ToString()
objBenchMark.FrequencyTypeToComplete = ddlFrequencyTypeComplete.SelectedValue.ToString()
objBenchMark.TimeToAcknowledge = Convert.ToInt32(txtTimeToAcknowledge.Text.ToString())
objBenchMark.TimeToComplete = Convert.ToInt32(txtTimeToComplete.Text.ToString())
If lblBenchMarkID.Text.ToString() = 0 Then
objBenchMark.BenchMarkID = 0
objBenchMark.CreateByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.InsertBechMarkData(objBenchMark)
Else
objBenchMark.BenchMarkID = Convert.ToInt32(lblBenchMarkID.Text.ToString())
objBenchMark.ModifiedByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.UpdateBechMarkData(objBenchMark)
End If
Next i
End If
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End Sub
Your data is not being saved, but the message telling you the data has been saved is being presented, despite it's saved or not.
Move thses lines inside the if-end if:
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"

How to keep user score in visual basic even if user failed validation first time?

Hello I am currently making an hangman game where you guess a randomly selected word and you have three rounds. Each time you win a round you gain 10 points, however if you don't guess the word before you run out of the 10 generous attempts. You will lose the round not gain anything.
After you win you three games of hangman, you are shown a new input text box in a high score form to input your name to save your high score to be displayed on the high score form and it has validation in (Meaning the user is required have at least one character inside the text box). This is where my main problem is, my input box will save your name and your points if you pass validation first time. However if you didn't pass validation first time but pass it the second time, your name is saved however your high score will be saved but only with one point. Sorry for my bad English, but is there anyway to keep the amount of points the user scores even if they failed validation first time instead of changing it to 1 point? Here is my code (Sorry for the bad indention):
Hangman Game Code (This is where the user gets their points from)
Imports System.IO
Public Class Hangman
'Public Variables
Public AttemptsLeft As Integer = 0
Public Rounds As Integer = 1
Public LetterChosen As Char
Dim EndWord() As Char
Dim AppPath As String = Application.StartupPath()
Dim FileRead() As String
Public GameWinner As Boolean = True
Dim HangmanShapes As New List(Of PowerPacks.Shape)
Public ScoreForRound As Integer
Dim NewControls As New List(Of Button)
Dim GameWord As New List(Of Label)
'Form Load code
Private Sub Hangman_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Load Word Game Code
If File.Exists(AppPath & "/wordlist.txt") Then
FileRead = IO.File.ReadAllLines(AppPath & "/wordlist.txt")
Dim RandomWord As New List(Of String)
For i = 0 To FileRead.Length - 1
RandomWord.Add(FileRead(i))
Next
Dim random As New Random() 'Using this to randomise each word
EndWord = RandomWord(random.Next(0, RandomWord.Count - 1)).ToUpper.ToCharArray 'Will put each character of the randomly chosen word into the labels.
Score.Text = UScore
Round.Text = Rounds
Letter1.Text = EndWord(0)
Letter1.Visible = False
Letter2.Text = EndWord(1)
Letter2.Visible = False
Letter3.Text = EndWord(2)
Letter3.Visible = False
Letter4.Text = EndWord(3)
Letter4.Visible = False
Letter5.Text = EndWord(4)
Letter5.Visible = False
Letter6.Text = EndWord(5)
Letter6.Visible = False
'Attempts left code
End If
With HangmanShapes
.Add(Attempt1)
.Add(Attempt2)
.Add(Attempt3)
.Add(Attempt4)
.Add(Attempt5)
.Add(Attempt6)
.Add(Attempt7)
.Add(Attempt8)
.Add(Attempt9)
.Add(Attempt10Part1)
.Add(Attempt10Part2)
End With
With NewControls
.Add(LetterA)
.Add(LetterB)
.Add(LetterC)
.Add(LetterD)
.Add(LetterE)
.Add(LetterF)
.Add(LetterG)
.Add(LetterH)
.Add(LetterI)
.Add(LetterJ)
.Add(LetterK)
.Add(LetterL)
.Add(LetterM)
.Add(LetterN)
.Add(LetterO)
.Add(LetterP)
.Add(LetterQ)
.Add(LetterR)
.Add(LetterS)
.Add(LetterT)
.Add(LetterU)
.Add(LetterV)
.Add(LetterW)
.Add(LetterX)
.Add(LetterY)
.Add(LetterZ)
End With
With GameWord
.Add(Me.Letter1)
.Add(Me.Letter2)
.Add(Me.Letter3)
.Add(Me.Letter4)
.Add(Me.Letter5)
.Add(Me.Letter6)
End With
End Sub
Private Sub AllBtnClicks(ByVal sender As System.Object, ByVal e As EventArgs) Handles LetterA.Click, LetterB.Click, LetterC.Click, LetterD.Click, LetterE.Click, LetterF.Click, LetterG.Click, LetterH.Click, LetterI.Click, LetterJ.Click, LetterK.Click, LetterL.Click, LetterM.Click, LetterN.Click, LetterO.Click, LetterP.Click, LetterQ.Click, LetterR.Click, LetterS.Click, LetterT.Click, LetterU.Click, LetterV.Click, LetterW.Click, LetterX.Click, LetterY.Click, LetterZ.Click
'Declartions
Dim LetterGuess As Button = sender
LetterGuess.Enabled = False
Dim LetterCorrect As Boolean = False
'Loop
For Each Letter In EndWord
If GetChar(LetterGuess.Name, 7) = Letter Then
Select Case Array.IndexOf(EndWord, Letter)
Case Is = 0
Letter1.Visible = True
Case Is = 1
Letter2.Visible = True
Case Is = 2
Letter3.Visible = True
Case Is = 3
Letter4.Visible = True
Case Is = 4
Letter5.Visible = True
Case Is = 5
Letter6.Visible = True
End Select
LetterCorrect = True
End If
Next
'Lives left code
If LetterCorrect = False Then
AttemptsLeft += 1
Select Case AttemptsLeft
Case 1
Attempt1.Visible = True
Attempts.Text = 1
Case 2
Attempt2.Visible = True
Attempts.Text = 2
Case 3
Attempt3.Visible = True
Attempts.Text = 3
Case 4
Attempt4.Visible = True
Attempts.Text = 4
Case 5
Attempt5.Visible = True
Attempts.Text = 5
Case 6
Attempt6.Visible = True
Attempts.Text = 6
Case 7
Attempt7.Visible = True
Attempts.Text = 7
Case 8
Attempt8.Visible = True
Attempts.Text = 8
Case 9
Attempt9.Visible = True
Attempts.Text = 9
Case 10
Attempt10Part1.Visible = True
Attempt10Part2.Visible = True
Attempts.Text = 10
LetterA.Enabled = False
LetterB.Enabled = False
LetterC.Enabled = False
LetterD.Enabled = False
LetterE.Enabled = False
LetterF.Enabled = False
LetterG.Enabled = False
LetterH.Enabled = False
LetterI.Enabled = False
LetterJ.Enabled = False
LetterK.Enabled = False
LetterL.Enabled = False
LetterM.Enabled = False
LetterN.Enabled = False
LetterO.Enabled = False
LetterP.Enabled = False
LetterQ.Enabled = False
LetterR.Enabled = False
LetterS.Enabled = False
LetterT.Enabled = False
LetterU.Enabled = False
LetterV.Enabled = False
LetterW.Enabled = False
LetterX.Enabled = False
LetterY.Enabled = False
LetterZ.Enabled = False
MsgBox("You have lost the round!")
ResetForm(0)
End Select
'Winning a round code
Else : Dim GameWinner As Boolean = True
Dim WordCheck As Label
For Each WordCheck In GameWord
If Not WordCheck.Visible Then
GameWinner = False
Exit For
End If
Next
If GameWinner Then
MsgBox("You have won the round!")
ResetForm(10)
'Losing a round code
End If
End If
End Sub
Private Sub ResetForm(ScoreForRound As Integer)
UScore += ScoreForRound
If Rounds = 3 Then
Me.Close()
HighScore.Show()
Else
Score.Text = +10
AttemptsLeft = 0
Attempts.Text = 0
Rounds += 1
Hangman_Load(Nothing, Nothing)
Dim HangmanReset As PowerPacks.Shape
For Each HangmanReset In HangmanShapes
HangmanReset.Visible = False
Next
Dim ControlReset As Control
For Each ControlReset In NewControls
ControlReset.Enabled = True
Next
End If
End Sub
End Class
High score form (This is where the user saves their points and also be able to view their high scores afterwards)
Imports System.IO
Public Class HighScore
Dim AppPath As String = Application.StartupPath()
Public Username As String
Private Sub HighScore_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileData() As String
Dim SizeArray As Integer
Try
FileData = File.ReadAllLines(AppPath & "/highscore.txt")
SizeArray = FileData.Length
Catch Break As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
For begin = 0 To SizeArray - 1 Step 1
Me.UserNameLabel.Text = UserNameLabel.Text & FileData(begin) & vbNewLine
Next
End Sub
Private Sub Backtomainmenu_Click(sender As Object, e As EventArgs) Handles Backtomainmenu.Click
MainMenu.Visible = True
Me.Visible = False
End Sub
Private Sub HelpButtonHighScore_Click(sender As Object, e As EventArgs) Handles HelpButtonHighScore.Click
MsgBox("This is the high score, this shows the top 10 players who achieved well in this game, this is ranked by the amount of points score. If you want to have your name in this high score, play the game well in order to achieve this.", MsgBoxStyle.Information)
End Sub
'This is where the user saves their high scores
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
End Sub
End Class
the user is required have at least one character inside the text box
Your code is currently saving to the file before any validation occurs:
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
After that block of code (which has already written to the file), then you're attempting to validate:
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Consolidate the code, and only write to the file if your validation is successful:
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text.Trim
If Username = "" Then
MsgBox("Enter a name please!")
Else
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
UScore = vbNull
Me.Close()
MainMenu.Show()
Catch ex As Exception
MsgBox("Error Saving High Score File!" & vbCrLf & vbCrLf & ex.ToString(), MsgBoxStyle.Critical)
End Try
End If
End Sub
With UScore = vbNull, you might be resetting the score even if NameInput.Text = "".
So, instead of
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Put UScore = vbNull inside the If statement so
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
UScore = vbNull 'Put it here instead
End If

VB.Net Global DataSets inside a public function

I am having some problem with a function that I hope you can help.
My Application is a simple one, it uses an Access database to load employee information and creates letters and financial breakdown sheet from word templates that users can then print and save back to the database.
I started by creating a dataset containing several datatables for each form subroutine but it resulted in literally hundreds of lines of repeated code. But it worked.
What I want to do, is have one dataset containing all the information needed about an employee and be able to reference it over several forms at the same time. So i created a public module that looks like this:
Public Module Datasets
Public update As String
Dim pCn As OleDb.OleDbConnection
Public Function CSofwareDataSet() As DataSet
'open new connection to database
pCn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\CGI Project\CorrespondenceSoftware\Database1.accdb; Persist Security Info=False;")
Try
Call pCn.Open() 'opens the connection
Catch ex As Exception
MessageBox.Show("Could not open a database connection! 1")
MessageBox.Show(ex.ToString)
End Try
CSofwareDataSet = New DataSet
Dim daOPG As New OleDb.OleDbDataAdapter("SELECT * FROM Overpayment WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Gross=1", pCn) 'get all data from Overpayment Details table
Dim daOPN As New OleDb.OleDbDataAdapter("SELECT * FROM Overpayment WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Net=1", pCn) 'get all data from Overpayment Details table
Dim daOPR As New OleDb.OleDbDataAdapter("SELECT * FROM OvpReasons", pCn) 'get overpayment reasons
Dim daREC As New OleDb.OleDbDataAdapter("SELECT * FROM TaxYear", pCn) 'get recovery date options
Dim daEMP As New OleDb.OleDbDataAdapter("SELECT * FROM EmployeeDetails WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Active=1 ", pCn) 'get all data from Employee Details table
Dim daCON As New OleDb.OleDbDataAdapter("SELECT * FROM Consultant", pCn) 'get all data from Consultant Details table
Dim daSET As New OleDb.OleDbDataAdapter("SELECT * FROM Settings", pCn) 'get all data from Consultant Details table
'Find the primary key (if missing)
daOPG.MissingSchemaAction = MissingSchemaAction.AddWithKey
daOPN.MissingSchemaAction = MissingSchemaAction.AddWithKey
daOPR.MissingSchemaAction = MissingSchemaAction.AddWithKey
daREC.MissingSchemaAction = MissingSchemaAction.AddWithKey
daEMP.MissingSchemaAction = MissingSchemaAction.AddWithKey
daCON.MissingSchemaAction = MissingSchemaAction.AddWithKey
daSET.MissingSchemaAction = MissingSchemaAction.AddWithKey
'setup prefixes
Dim cbOPG As New OleDb.OleDbCommandBuilder(daOPG)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbOPN As New OleDb.OleDbCommandBuilder(daOPN)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbOPR As New OleDb.OleDbCommandBuilder(daOPR)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbREC As New OleDb.OleDbCommandBuilder(daREC)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbEMP As New OleDb.OleDbCommandBuilder(daEMP)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
Dim cbCON As New OleDb.OleDbCommandBuilder(daCON)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
Dim cbSET As New OleDb.OleDbCommandBuilder(daSET)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
If CSofwareDataSet.HasChanges Then
Try
daEMP.Update(CSofwareDataSet, "EmployeeDetails")
daOPG.Update(CSofwareDataSet, "OverPaymentGross")
daOPN.Update(CSofwareDataSet, "OverPaymentNet")
daSET.Update(CSofwareDataSet, "Settings")
MessageBox.Show("Success! Records updated.")
update = "0"
Catch ex As Exception
MessageBox.Show("Oops - something went wrong and it didn't update")
update = "0"
End Try
ElseIf CSofwareDataSet.Tables.Count = 0 Then
daOPG.Fill(CSofwareDataSet, "OverPaymentGross")
daOPN.Fill(CSofwareDataSet, "OverPaymentNet")
daOPR.Fill(CSofwareDataSet, "OverPaymentReasons")
daREC.Fill(CSofwareDataSet, "RecoveryDates")
daEMP.Fill(CSofwareDataSet, "EmployeeDetails")
daCON.Fill(CSofwareDataSet, "ConsultantDetails")
daSET.Fill(CSofwareDataSet, "Settings")
End If
'If update = "1" Then
' Try
' daEMP.Update(CSofwareDataSet, "EmployeeDetails")
' daOPG.Update(CSofwareDataSet, "OverPaymentGross")
' daOPN.Update(CSofwareDataSet, "OverPaymentNet")
' daSET.Update(CSofwareDataSet, "Settings")
'
' MessageBox.Show("Success! Records updated.")
' update = "0"
' Catch ex As Exception
' MessageBox.Show("Oops - something went wrong and it didn't update")
' update = "0"
' End Try
' End If
pCn.Close()
End Function
End Module
On each form, it gets referenced like this (as an example):
Imports WeifenLuo.WinFormsUI.Docking
Imports Word = Microsoft.Office.Interop.Word
Imports CorrespondenceSoftware.Datasets
Public Class GrossInput
Dim loading = "1"
Dim NewEmployee = "0" 'sets the default new employee flag to 0
Private pCn As OleDb.OleDbConnection
Private Sub GrossInput_Load(ByVal Sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Try
If CSofwareDataSet.Tables("EmployeeDetails").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("EmployeeDetails").Rows.Count - 1
cbTitle.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(2)
tbFName.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(3)
tbLName.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(4)
tbAddress1.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(5)
tbAddress2.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(6)
tbAddress3.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(7)
tbAddress4.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(8)
tbPostcode.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(9)
tbWorkLocation.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(10)
tbWorkLocation.Enabled = False
tbPostcode.Enabled = False
tbAddress4.Enabled = False
tbAddress3.Enabled = False
tbAddress2.Enabled = False
tbAddress1.Enabled = False
tbLName.Enabled = False
tbFName.Enabled = False
cbTitle.Enabled = False
chkMSC.Enabled = False
chkOfficer.Enabled = False
chkStaff.Enabled = False
bnSaveEmp.Enabled = False
bnEditEmp.Enabled = True
Next
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(11) = "1" Then
chkOfficer.Checked = True
Else
chkOfficer.Checked = False
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(12) = "1" Then
chkStaff.Checked = True
Else
chkStaff.Checked = False
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(13) = "1" Then
chkMSC.Checked = True
Else
chkMSC.Checked = False
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
MessageBox.Show("Employee not found. Ensure pay number is correct and create a new record")
NewEmployee = "1" ' tells the program to create a new record if saved
cbReference.Enabled = False
cbReference.Text = ""
bnEditEmp.Enabled = False
End Try
'display the overpayment references to the user
If CSofwareDataSet.Tables("OverPaymentGross").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("OverPaymentGross").Rows.Count - 1
cbReference.Items.Add(CSofwareDataSet.Tables("OverPaymentGross").Rows(i)(2))
Next
End If
'display the available consultants to the user
If CSofwareDataSet.Tables("ConsultantDetails").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("ConsultantDetails").Rows.Count - 1
cbConsultant.Items.Add(CSofwareDataSet.Tables("ConsultantDetails").Rows(i)(1) & " " & CSofwareDataSet.Tables("ConsultantDetails").Rows(i)(2))
Next
End If
'display the available Overpayment reasons to the user
If CSofwareDataSet.Tables("OverPaymentReasons").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("OverPaymentReasons").Rows.Count - 1
cbReason.Items.Add(CSofwareDataSet.Tables("OverPaymentReasons").Rows(i)(1))
Next
End If
'Load other recovery date options
If CSofwareDataSet.Tables("RecoveryDates").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("RecoveryDates").Rows.Count - 1
cbStartRecovery.Items.Add(CSofwareDataSet.Tables("RecoveryDates").Rows(i)(1))
Next
End If
Catch ex As Exception
MessageBox.Show(ex.ToString) 'Show any errors to the user
End Try
loading = "0"
End Sub
Now! the problem that I'm having is that, this does work and run without any errors BUT every time the CSSoftwareDataSet function runs it populates the tables correctly and returns the expected results but it then deletes the datatable data so every time the function is referenced from a winform it needs to haul all the data from the access database from scratch, severely impacting on the performance of the program. The tables wont update properly because its not storing the datatable information and as soon as its inserted its forgotten but again, produces no errors. An example of my update script looks like this:
Else 'create a new record
'create a new reference
Dim REFRowCount = CSofwareDataSet.Tables("OverPaymentGross").Rows.Count + 1 'count the number of rows in table and add 1
Dim NewREF = "OVPG" & Main.tbPayNumber.Text & "-" & REFRowCount
'Find todays date and reply dates
Dim TodayDatedate = Format(Now.Date(), "dd/MM/yyyy")
Dim ReplyDatedate = Format(Now.Date.AddDays(21), "dd/MM/yyyy")
'Create a new row
Dim OPNew As DataRow = CSofwareDataSet.Tables("OverPaymentGross").NewRow() 'create a variable to contain the new row
OPNew.Item(1) = Main.tbPayNumber.Text
OPNew.Item(2) = NewREF
OPNew.Item(3) = tbOverpaymentAmount.Text.ToString
OPNew.Item(4) = tbMonRec.Text
OPNew.Item(5) = tbTaxP.Text
OPNew.Item(6) = TodayDatedate
OPNew.Item(7) = ReplyDatedate
OPNew.Item(8) = tbMoRep.Text
OPNew.Item(9) = cbStartRecovery.Text
OPNew.Item(10) = "1" 'Set as gross
OPNew.Item(11) = "0" 'do not set as net
OPNew.Item(12) = cbReason.Text
OPNew.Item(13) = tbAI.Text
OPNew.Item(14) = dtpStart.Value.Date
OPNew.Item(15) = dtpFinish.Value.Date
OPNew.Item(16) = cbConsultant.Text
OPNew.Item(17) = tbPosition.Text
Call CSofwareDataSet.Tables("OverPaymentGross").Rows.Add(OPNew) 'fill the new row and insert the data
There must be a solution to this. To create a dataset that holds its data in session while you open other winforms until it is reset. I'm out of ideas because i really don't want to go back to repeating all this code for practically every subroutine in my program.
I hope I've explained it OK .. Any help here will be greatly appreciated.
Many thanks,
Shane
You can declare the DataSet globally, populate it in a function (sub), which is called just at the start, and retrieve the information by accessing the variable rather than by calling the function over and over. Your code uses a somehow ambiguous approach (same name for function and for variable) which, together with the VB rules (functions might not include a Return statement but a variable with the function's name) does not play to your favor.
Sample code converting the DataSet into a public variable and renaming the function (and converting it into a sub: what is the point of a function now?):
Public CSofwareDataSet As DataSet
Public Sub populateDS()
'open new connection to database
pCn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\CGI Project\CorrespondenceSoftware\Database1.accdb; Persist Security Info=False;")
Try
Call pCn.Open() 'opens the connection
Catch ex As Exception
MessageBox.Show("Could not open a database connection! 1")
MessageBox.Show(ex.ToString)
End Try
CSofwareDataSet = New DataSet
'Remaining code
End Sub
Call this sub just once (right at the start of your application; or every time new data has to be retrieved from the DB) and continue using CSofwareDataSet as so far (although as a variable, by removing the Call bits; which, on the other hand, are not required in VB.NET at all).

Input a button's text into a text box

Following on from my last Question Buttons to be renamed by the user which was answered quickly and helped a lot.
At the moment I have got this code, which I need to have on 100's of buttons.
What I need to know is how to use the text from the button to put into the different text boxes that requires them.
If Label4.Text = "Admin" Then
With DirectCast(sender, Button)
.Text = InputBox("Button Name", "Button Name", .Text)
End With
Else
Me.TransactionBindingSource.AddNew()
Product_NameTextBox.Text = >>>>>>Button name<<<<<<<<
Try
Me.ProductTableAdapter.FillByProductName(Me.Database1DataSet.Product, Product_NameTextBox.Text)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
ProductTextBox.Text = >>>>>>>Button2.Text<<<<<<<<
GroupTextBox.Text = GroupTextBox1.Text
AmountTextBox.Text = AmountTextBox1.Text
PriceTextBox.Text = PriceTextBox1.Text
TimeTextBox.Text = TimeOfDay
DateTextBox.Text = DateString
Me.Validate()
Me.TransactionBindingSource.EndEdit()
Me.TransactionTableAdapter.Update(Me.Database1DataSet)
Timer2.Enabled = True
TransNameLB.Items.Add(>>>>>>>Button2.Text<<<<<<<<)
TransPriceLB.Items.Add(PriceTextBox.Text)
Dim sum As Double
For x As Integer = 0 To TransPriceLB.Items.Count - 1
sum += Val(TransPriceLB.Items.Item(x).ToString)
Next
TextBox1.Text = sum.ToString
QTYDrinksTB.Text = TransNameLB.Items.Count
End If
End Sub
Everything works apart from the bits between >>> <<<, where I need to get the button that is clicked and return the text from the button into the text boxes/list box.
I have 100's of buttons that need this code.
You use With DirectCast(sender, Button) from your previous question, which can also be used to help with your other parts. For example:
If Label4.Text = "Admin" Then
With DirectCast(sender, Button)
.Text = InputBox("Button Name", "Button Name", .Text)
End With
Else
Me.TransactionBindingSource.AddNew()
With DirectCast(sender, Button)
Product_NameTextBox.Text = .Text
Try
Me.ProductTableAdapter.FillByProductName(Me.Database1DataSet.Product, Product_NameTextBox.Text)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
ProductTextBox.Text = .Text
GroupTextBox.Text = GroupTextBox1.Text
AmountTextBox.Text = AmountTextBox1.Text
PriceTextBox.Text = PriceTextBox1.Text
TimeTextBox.Text = TimeOfDay
DateTextBox.Text = DateString
Me.Validate()
Me.TransactionBindingSource.EndEdit()
Me.TransactionTableAdapter.Update(Me.Database1DataSet)
Timer2.Enabled = True
TransNameLB.Items.Add(.Text)
TransPriceLB.Items.Add(PriceTextBox.Text)
End With
Dim sum As Double
For x As Integer = 0 To TransPriceLB.Items.Count - 1
sum += Val(TransPriceLB.Items.Item(x).ToString)
Next
TextBox1.Text = sum.ToString
QTYDrinksTB.Text = TransNameLB.Items.Count
End If