I have a DataGridView that updates a database. Roger helped me with it and it works great.
When I close the app and open it back up the DataGridView rows are not populated again from the database.
All the information is in the database and in the DataSet, but is not being "filled" back into the DataGridView.
This code is in the Form1_Load event. It looks like this should be doing the fill. I don't understand why this doesn't fill the DataGridView rows on form load:
'get the job titles for the applicants
For Each dgvr As DataGridViewRow In ApplicantsDataGridView.Row
s
fillInTitle(dgvr)
Next
Here's the fillInTitle sub:
Private Sub fillInTitle(ByVal dgvr As DataGridViewRow)
'check if there is a value in the third cell ...
'... (index 2, which is the "Job" field ...
'... in this row from the datagridview
If TypeOf dgvr.Cells(2).Value Is DBNull Then
'if not, then there is no Job Title
dgvr.Cells(4).Value = ""
Else
'if there is, use it to get the Job Title
dgvr.Cells(4).Value = getTitleFromID(CInt(dgvr.C
ells(2).Va
lue))
End If
End Sub
Thanks.
David
Below is the whole Form1.vb code for reference:
--------------------------
----------
----------
----------
----------
----------
----------
----------
----------
--
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
'Look up some of the instructions on "refreshing" a DataGridView from the database...
Public Class Form1
Private dtApplicants As New DataTable("Applicants")
Private cmApplicants As CurrencyManager
Private dtJobs As New DataTable("Jobs")
Private dvjobs As New DataView
Private WithEvents cmJobs As CurrencyManager
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'SYEP2007DataSet.JobTitles
' table. You can move, or remove it, as needed.
Me.ApplicantsTableAdapter.
Fill(Me.SY
EP2007Data
Set.Applic
ants)
Me.JobTitlesTableAdapter.F
ill(Me.SYE
P2007DataS
et.JobTitl
es)
dtApplicants = Me.SYEP2007DataSet.Applica
nts
dtJobs = Me.SYEP2007DataSet.JobTitl
es
'filltables() 'equivalent to filling tables with ...
'... a dataadapter or a tableadapter
'get and display the count of applicant records
Dim count As Integer = dtApplicants.Rows.Count
txtTotalApplicants.Text = String.Format("{0} Applicants", count)
'bind the applicants table to the datagridview
ApplicantsDataGridView.Dat
aSource = dtApplicants
'set up the currencymanager - convenient for referring ...
'... to the currently selected row in the applicants grid
cmApplicants = CType(BindingContext(dtApp
licants), CurrencyManager)
'set up a dataview to filter the jobs table so it ...
'... only shows those where some jobs remain available
dvjobs.Table = dtJobs
dvjobs.RowFilter = "txtWorksiteJobTitlePositi
onsNumber > 0"
'bind the jobs table to the datagridview
JobTitlesDataGridView.Data
Source = dvjobs
'set up the currency manager
cmJobs = CType(BindingContext(dvjob
s), CurrencyManager)
'customise the grids - with a strongly typed dataset ...
'... this could be done in the designer
ApplicantsDataGridView.Rea
dOnly = True
ApplicantsDataGridView.All
owUserToAd
dRows = False
'hide the applicant ID
ApplicantsDataGridView.Col
umns(0).Vi
sible = False
'hide the job ID ...
ApplicantsDataGridView.Col
umns(2).Vi
sible = False
'hide the ProgramID column in Applicants DGV
ApplicantsDataGridView.Col
umns(3).Vi
sible = False
'... but add an unbound column to show ...
'... the job title matching that ID
Dim TitleCol As New DataGridViewTextBoxColumn
TitleCol.HeaderText = "Job Title"
ApplicantsDataGridView.Col
umns.Add(T
itleCol)
Dim NumberofAdults As New DataGridViewTextBoxColumn
NumberofAdults.HeaderText = "Adults"
ApplicantsDataGridView.Col
umns.Add(N
umberofAdu
lts)
JobTitlesDataGridView.Read
Only = True
JobTitlesDataGridView.Allo
wUserToAdd
Rows = False
JobTitlesDataGridView.Colu
mns(0).Vis
ible = False
ApplicantsDataGridView.Col
umns(1).Wi
dth = 100
'run the sub to fill the jobs numbers displays
updateTotals()
'get the job titles for the applicants
For Each dgvr As DataGridViewRow In ApplicantsDataGridView.Row
s
fillInTitle(dgvr)
Next
TabControl1.SelectedIndex = 1
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.Canc
elEventArg
s) Handles MyBase.Closing
'make sure any outstanding edits are committed to the datatables
cmApplicants.EndCurrentEdi
t()
cmJobs.EndCurrentEdit()
'then save datatable changes to database
Me.ApplicantsTableAdapter.
Update(Me.
SYEP2007Da
taSet.Appl
icants)
Me.JobTitlesTableAdapter.U
pdate(Me.S
YEP2007Dat
aSet.JobTi
tles)
End Sub
Private Sub btnUpdatePosition_Click(By
Val sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdatePosition.Click
Dim jobRow As DataRow()
'use the currency manager to get the currently ...
'... selected job in the jobs grid
Dim jobsRow As DataRowView = CType(cmJobs.Current, DataRowView)
'and save the job number
Dim newJobNumber As Integer = CInt(jobsRow("keyJobTitleI
D"))
'similar for the applicants
Dim applicantsRow As DataRowView = CType(cmApplicants.Current
, DataRowView)
'check if this applicant already has a job
If Not TypeOf (applicantsRow.Item("keyJo
bTitleID")
) Is DBNull Then
'if so, seek the relevant row from the datatable
jobRow = dtJobs.Select("keyJobTitle
ID = " & Convert.ToString(applicant
sRow.Item(
"keyJobTit
leID")))
'if there is one
If jobRow.Length > 0 Then
'it will be the first in the row array: update it
Dim myVal As Integer = CInt(jobRow(0).Item("txtWo
rksiteJobT
itlePositi
onsNumber"
))
myVal += 1 'or myVal = myVal + 1
jobRow(0).Item("txtWorksit
eJobTitleP
ositionsNu
mber") = myVal
Else
'if there isn't one ...
MsgBox("Something wrong")
End If
End If
'put the new job number in the applicant's record
applicantsRow.Item("keyJob
TitleID") = newJobNumber
'decrement the number of jobs available
'seek the relevant row from the datatable
jobRow = dtJobs.Select("keyJobTitle
ID = " & newJobNumber)
'if there is one
If jobRow.Length > 0 Then
'it will be the first in the row array: update it
Dim myVal As Integer = CInt(jobRow(0).Item("txtWo
rksiteJobT
itlePositi
onsNumber"
))
myVal -= 1 'or myVal = myVal - 1
jobRow(0).Item("txtWorksit
eJobTitleP
ositionsNu
mber") = myVal
Else
'if there isn't one ...
MsgBox("Something wrong")
End If
''commit the edits - this is necessary where ...
''... they have been done by via the currency ...
''... manager's Current record, rather than ...
''... (as above) in the datatable itself
cmApplicants.EndCurrentEdi
t()
cmJobs.EndCurrentEdit()
'run the sub to update the jobs numbers displays
updateTotals()
'get the job title for this applicant
Dim dgvr As DataGridViewRow = ApplicantsDataGridView.Cur
rentRow
fillInTitle(dgvr)
End Sub
Private Sub btnCancelPosition_Click(By
Val sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelPosition.Click
Me.Close()
End Sub
Private Sub cmJobs_PositionChanged(ByV
al sender As Object, ByVal e As System.EventArgs) Handles cmJobs.PositionChanged
'the jobs currency manager was declared WithEvents ...
'... to make it easy to update the jobs numbers ...
'... displays when a different job was selected ...
'... in the grid
If cmJobs.Count > 0 Then
updateTotals()
End If
End Sub
Private Sub updateTotals()
If cmJobs.Count = 0 Then
txtAvailable.Text = ""
txtTaken.Text = ""
txtTotal.Text = ""
MsgBox("No more jobs")
Exit Sub
End If
'use the currency manager to get the currently ...
'... selected job in the jobs grid
Dim jobsRow As DataRowView = CType(cmJobs.Current, DataRowView)
'that says how many of that job are available
Dim available As Integer = CInt(jobsRow.Item("txtWork
siteJobTit
lePosition
sNumber"))
'get the job ID from that row
Dim thisJob As Integer = CInt(jobsRow.Item("keyJobT
itleID"))
'use the job ID to find how many applicants ...
'... already have that job
Dim taken As Integer = CInt(dtApplicants.Compute(
"Count(key
JobTitleID
)", "keyJobTitleID = " & thisJob))
'the total is the sum of those two
Dim total As Integer = available + taken
'display the results
txtAvailable.Text = available.ToString
txtTaken.Text = taken.ToString
txtTotal.Text = total.ToString
End Sub
Private Function getTitleFromID(ByVal ID As Integer) As String
'Temporary line for debugging purposes
'If that is reporting 0, then we know the problem is with the datatable.
'If it is reporting more than that, then the problem is with either the value
'that is being passed to the function,
'or with the syntax or references in the select statement.
' 'Debug.WriteLine(dtJobs.Ro
ws.Count)
'use datatable filter to return only rows with this ID
Dim dr As DataRow() = dtJobs.Select("keyJobTitle
ID = " & ID)
'check if there are any such rowsI
If dr.Length > 0 Then
'if yes, there should only be one - in position 0
'return the value in the JobNmae field from that
Return CStr(dr(0)("txtWorksiteJob
Title"))
Else
'otherwise, return empty string
Return ""
End If
End Function
Private Sub fillInTitle(ByVal dgvr As DataGridViewRow)
'check if there is a value in the third cell ...
'... (index 2, which is the "Job" field ...
'... in this row from the datagridview
If TypeOf dgvr.Cells(2).Value Is DBNull Then
'if not, then there is no Job Title
dgvr.Cells(4).Value = "" 'I added the ProgramID field and changed Cells(3) to Cells(4) (added on line 55)
Else
'if there is, use it to get the Job Title
dgvr.Cells(4).Value = getTitleFromID(CInt(dgvr.C
ells(2).Va
lue)) 'I added the ProgramID field and changed Cells(3) to Cells(4)
End If
End Sub
Private Sub ApplicantsDataGridView_Dat
aError(ByV
al sender As Object, ByVal e As System.Windows.Forms.DataG
ridViewDat
aErrorEven
tArgs) Handles ApplicantsDataGridView.Dat
aError
Debug.WriteLine(e.ColumnIn
dex)
Debug.WriteLine(e.RowIndex
)
Debug.WriteLine(Applicants
DataGridVi
ew.Rows(e.
RowIndex).
Cells(e.Co
lumnIndex)
.Value)
Debug.WriteLine(Applicants
DataGridVi
ew.Rows(e.
RowIndex).
Cells(e.Co
lumnIndex)
.EditedFor
mattedValu
e)
e.ThrowException = True
End Sub
End Class
Start Free Trial