Reputation: 863
Howdy, So this was a homework assignment and in short the instructor gave up on me. When I run my program I get this error message. I tried commenting out the lines of code for that bind and when I ran the program it gave me the same error on the next bind (about three rows down).
I sent the program to my instructor and he said the program runs but my forms were not loading or accessing the database correctly, which is something I can't see since every time I run this program I get this error.
The assignment is overdue and I just had to take a mulligan but more importantly I'm really annoyed that he didn't try to help me on it. His response is simply "I don't see the error" even after I sent him screen captures. I'd really like to figure out what is wrong. I am wondering if it is my machine since it seems to only happen on my machine? If so is there something I should be updating? How would I check? I don't want to fail any other assignments because of this.
Here is a copy of my database code:
Option Strict Off
Option Explicit On
Imports System.Data
Public Class DataClass
'Declare Class Level Variables
Private CategoryProductDataSet As CategoryProductDataSet
Private JobsEmployeesDataSet As NORTHWNDDataSet
'Declare table adapters for the categories form
Private ProductsTableAdapter As _
CategoryProductDataSetTableAdapters.ProductsTableAdapter
Private CategoriesTableAdapter As _
CategoryProductDataSetTableAdapters.CategoriesTableAdapter
' Declare Table Adapters for Employees and Jobs
Private CustomersTableAdapter As _
NORTHWNDDataSetTableAdapters.CustomersTableAdapter
Private OrdersTableAdapter As _
NORTHWNDDataSetTableAdapters.OrdersTableAdapter
Private EmployeeTableAdapter As _
NORTHWNDDataSetTableAdapters.EmployeesTableAdapter
'Declare data relation for products form
Private ProductsToCategories As DataRelation
'================================================================================
'Create new constructor for class
Public Sub New()
Try
'Instantiate data sets
With Me
.CategoryProductDataSet = New CategoryProductDataSet
.JobsEmployeesDataSet = New NORTHWNDDataSet
'instantiate the table adapters
.ProductsTableAdapter = _
New CategoryProductDataSetTableAdapters.ProductsTableAdapter
.CategoriesTableAdapter = _
New CategoryProductDataSetTableAdapters.CategoriesTableAdapter
.CustomersTableAdapter = _
New NORTHWNDDataSetTableAdapters.CustomersTableAdapter
.OrdersTableAdapter = _
New NORTHWNDDataSetTableAdapters.OrdersTableAdapter
'New NORTHWNDDataSetTableAdapters.CustOrdersOrdersTableAdapter
.EmployeeTableAdapter = _
New NORTHWNDDataSetTableAdapters.EmployeesTableAdapter
'assign products DataRelation to dataset
.ProductsToCategories = CategoryProductDataSet.Relations!ProductsToCategories
'Fill CategoryProductdataSet using the fill method
.CategoriesTableAdapter.Fill(.CategoryProductDataSet.Categories)
.ProductsTableAdapter.Fill(.CategoryProductDataSet.Products)
'Fill NORTHWNDDataSet using fill method
.CustomersTableAdapter.Fill(JobsEmployeesDataSet.Customers)
.OrdersTableAdapter.Fill(JobsEmployeesDataSet.Orders)
.EmployeeTableAdapter.Fill(JobsEmployeesDataSet.Employees)
End With
Catch ex As Exception
End Try
End Sub
Public Function GetJobsEmployeeDataSet() As NORTHWNDDataSet
'Return the dataset
Return JobsEmployeesDataSet
End Function
Public Function GetCategoryProductDataSet() As CategoryProductDataSet
'Return the dataset
Return CategoryProductDataSet
End Function
Public Sub UpdateDataSet(ByVal ADataSet As CategoryProductDataSet)
Try
'update child deletes
If CategoryProductDataSet.Products.GetChanges(DataRowState.Deleted) _
IsNot Nothing Then
'Get changes for delted child rows
Dim ProductsDeletedDataTable As DataTable
ProductsDeletedDataTable = ADataSet.Categories.GetChanges( _
DataRowState.Deleted)
ProductsTableAdapter.Update(ProductsDeletedDataTable
)
'update parent rows
If CategoryProductDataSet.Products.GetChanges IsNot Nothing Then
ProductsTableAdapter.Update(ADataSet.Products)
End If
'update child rows'
If CategoryProductDataSet.Products.GetChanges(DataRowState.Added + _
DataRowState.Modified) IsNot _
Nothing Then
'Get changes for the child rows
Dim ProductsAddDataTable As DataTable
ProductsAddDataTable = ADataSet.Products.GetChanges( _
DataRowState.Added + DataRowState.Modified)
ProductsTableAdapter.Update(ProductsAddDataTable)
End If
End If
Catch ex As Exception
MessageBox.Show("Unable to update database.", "Update Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
End Try
End Sub
End Class
Here is a copy of the form code:
Option Strict Off
Option Explicit On
Imports System.Data
Public Class ProductCategoriesForm
'declare module level variables
Private ProductCategories As DataClass
Private ProductCategoriesDataSet As CategoryProductDataSet
Private ProductsTableAdapter As _
NORTHWNDDataSetTableAdapters.ProductsTableAdapter
Private CategoriesTableAdapter As _
NORTHWNDDataSetTableAdapters.CategoriesTableAdapter
Private WithEvents ProductsBindingSource As BindingSource
Private WithEvents CategoriesBindingSource As BindingSource
Private AddingBoolean As Boolean
Private ClosingBoolean As Boolean
Private EditingBoolean As Boolean
Private GridInitializedBoolean As Boolean
Private ProductIDString As String 'holds product ID
Private Sub ProductCategoriesForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Try
ProductCategories = New DataClass
ProductCategoriesDataSet = New CategoryProductDataSet
ProductCategoriesDataSet = ProductCategories.GetCategoryProductDataSet
'Set up binding source
ProductsBindingSource = New BindingSource
CategoriesBindingSource = New BindingSource
With ProductsBindingSource
.DataSource = ProductsBindingSource
.DataMember = "Products"
.Sort = "ProductID"
End With
With CategoriesBindingSource
.DataSource = CategoriesBindingSource
.DataMember = "ProductsToCategories"
End With
Catch ex As Exception
End Try
'Establish Record Count
ProductsBindingSource.MoveLast()
ProductsBindingSource.MoveFirst()
'Bind the textboxes
CategoryTextBox.DataBindings.Add("text", _
CategoriesBindingSource, "CategoryName")
CategoryIDTextBox.DataBindings.Add("text", _
CategoriesBindingSource, "CategoryID")
DescriptionTextBox.DataBindings.Add("text", _
CategoriesBindingSource, "Description")
'Initialize binding for products data grid view
If Not GridInitializedBoolean Then
ProductDataGridView.DataSource = _
ProductsBindingSource
SetUpGridColumns()
GridInitializedBoolean = True
End If
'filter products by category ID
ProductsBindingSource.Filter = "CategoryID = '" & _
CategoryIDTextBox.Text & "'"
End Sub
Private Sub ProductCategoriesForm_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
'Check for unsaved changes
If ProductCategoriesDataSet.HasChanges Then
Dim ResponseDialogResult As DialogResult
ResponseDialogResult = MessageBox.Show("Save the database changes?", _
"Unsaved Changes", MessageBoxButtons.YesNoCancel, _
MessageBoxIcon.Question)
Select Case ResponseDialogResult
Case Windows.Forms.DialogResult.Yes
ProductCategories.UpdateDataSet(ProductCategoriesDataSet)
Case Windows.Forms.DialogResult.Cancel
e.Cancel = True
End Select
End If
End Sub
'Create a sub routine to set up the grid columns and set the column widths'
Private Sub SetUpGridColumns()
Try
With Me.ProductDataGridView
'Set up column headers
.Columns!ProductID.HeaderText = "Product ID"
.Columns!ProductName.HeaderText = "Product Name"
.Columns!SupplierID.HeaderText = "Supplier ID"
.Columns!CategoryID.HeaderText = "Category ID"
.Columns!QuanityPerUnit.HeaderText = "Quantity Per Unit"
.Columns!UnitPrice.HeaderText = "Unit Price"
.Columns!UnitsInStock.HeaderText = "Units In Stock"
.Columns!UnitsOnORder.HeaderText = "Units On Order"
.Columns!ReorderLevel.HeaderText = "Reorder Level"
.Columns!Discontinued.HeaderText = "Discontinued"
'set up column widths'
.Columns!ProductID.Width = 100
.Columns!ProductName.Width = 75
.Columns!SupplierID.Width = 30
.Columns!CategoryID.Width = 75
.Columns!QuanityPerUnit.Width = 35
.Columns!UnitPrice.Width = 50
.Columns!UnitsInStock.Width = 50
.Columns!UnitsOnORder.Width = 50
.Columns!ReorderLevel.Width = 50
.Columns!Discontinued.Width = 50
End With
Catch ex As Exception
End Try
End Sub
Private Sub FirstButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FirstButton.Click
'move to first record
ProductsBindingSource.MoveFirst()
'Initilize binding for products data grid view
If Not GridInitializedBoolean Then
'Bind and format the grid
ProductDataGridView.DataSource = _
ProductsBindingSource
SetUpGridColumns()
GridInitializedBoolean = True
End If
'Filter products by category ID
ProductsBindingSource.Filter = "CategoryID = '" & _
CategoryIDTextBox.Text & "'"
End Sub
Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click
'move to the previous record
With ProductsBindingSource
If .Position = 0 Then
.MoveLast()
Else
.MovePrevious()
End If
'Initilize binding for products data grid view
If Not GridInitializedBoolean Then
'Bind and format the grid
ProductDataGridView.DataSource = _
ProductsBindingSource
SetUpGridColumns()
GridInitializedBoolean = True
End If
'Filter products by category ID
ProductsBindingSource.Filter = "CategoryID = '" & _
CategoryIDTextBox.Text & "'"
End With
End Sub
Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click
'move to next record
With ProductsBindingSource
If .Position = .Count - 1 Then
.MoveFirst()
Else
.MoveNext()
End If
End With
'Initilize binding for products data grid view
If Not GridInitializedBoolean Then
'Bind and format the grid
ProductDataGridView.DataSource = _
ProductsBindingSource
SetUpGridColumns()
GridInitializedBoolean = True
End If
'Filter products by category ID
ProductsBindingSource.Filter = "CategoryID = '" & _
CategoryIDTextBox.Text & "'"
End Sub
Private Sub LastButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LastButton.Click
'Move to last record
ProductsBindingSource.MoveLast()
'Initilize binding for products data grid view
If Not GridInitializedBoolean Then
'Bind and format the grid
ProductDataGridView.DataSource = _
ProductsBindingSource
SetUpGridColumns()
GridInitializedBoolean = True
End If
'Filter products by category ID
ProductsBindingSource.Filter = "CategoryID = '" & _
CategoryIDTextBox.Text & "'"
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
Private Sub ProductsBindingSource_PositionChanged _
(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles ProductsBindingSource.PositionChanged
'Display the position and number of records
With Me.ProductsBindingSource
Me.ToolStripStatusLabel1.Text = _
"record " & (.Position + 1).ToString & _
" of " & .Count.ToString
End With
End Sub
Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
Try
If AddButton.Text = "&Add" Then
With ProductsBindingSource
.EndEdit()
.AddNew()
End With
AddingBoolean = True
CategoryIDTextBox.Focus()
SetNavigation(False)
SetControlsReadOnly(False)
SetButtonsForEdit()
Else
'save has been clicked
ProductsBindingSource.EndEdit()
SaveDataSet()
ToolStripStatusLabel2.Text = "Record Saved"
AddingBoolean = False
EditingBoolean = False
SetNavigation(True)
SetControlsReadOnly(True)
ResetButtonsAfterEdit()
End If
Catch ex As Exception
'catch duplicate records and constraint violations
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetNavigation(ByVal ValueBoolean As Boolean)
'Set the enabled property of the navigation
With Me
.FirstButton.Enabled = ValueBoolean
.LastButton.Enabled = ValueBoolean
.NextButton.Enabled = ValueBoolean
.PreviousButton.Enabled = ValueBoolean
End With
End Sub
Private Sub SetControlsReadOnly(ByVal ValueBoolean As Boolean)
'Locks or unlocks controls
With Me
.CategoryTextBox.ReadOnly = ValueBoolean
.CategoryIDTextBox.ReadOnly = ValueBoolean
.DescriptionTextBox.ReadOnly = ValueBoolean
End With
End Sub
Private Sub SetButtonsForEdit()
'set up the buttons for an add or edit
With Me
.AddButton.Text = "&Save"
.DeleteButton.Text = "&Cancel"
.EditButton.Enabled = True
.ToolStripStatusLabel2.Text = String.Empty
End With
End Sub
Private Sub ResetButtonsAfterEdit()
'reset the buttons after the add or edit is completed
With Me
.AddButton.Text = "&Add"
.DeleteButton.Text = "&Delete"
.EditButton.Enabled = True
.ToolStripStatusLabel2.Text = String.Empty
End With
End Sub
Private Sub EditButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles EditButton.Click
'Allows user to edit the current record
With Me
.EditingBoolean = True
.SetNavigation(False)
.SetControlsReadOnly(False)
.SetButtonsForEdit()
End With
End Sub
Private Sub DeleteButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles DeleteButton.Click
'Delete the current record after confirming or cancel an add or edit
Dim DeleteDialogResult As DialogResult
With Me
Try
If .DeleteButton.Text = "&Delete" Then
DeleteDialogResult = MessageBox.Show("Delete this record?", _
"Confirm Delete", MessageBoxButtons.YesNo, _
MessageBoxIcon.Question)
If DeleteDialogResult = Windows.Forms.DialogResult.Yes Then
.ProductsBindingSource.RemoveCurrent()
'.ProductsTableAdapter.Update(CategoryProductDataSet.Products)
.ToolStripStatusLabel2.Text = "Record Deleted"
End If
Else
'cancel button was clicked
.ProductsBindingSource.CancelEdit()
.AddingBoolean = False
.EditingBoolean = False
.SetNavigation(True)
.SetControlsReadOnly(True)
.ResetButtonsAfterEdit()
End If
Catch ex As Exception
Dim Messagestring As String
Messagestring = "Unable to complete the delete/cancel: " _
& ex.Message
MessageBox.Show(Messagestring, "Delete/Cancel Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End With
End Sub
Private Sub SaveDataSet()
'save the dataset back to the original data source
With Me
If .ProductCategoriesDataSet.HasChanges Then
Try
.Validate()
.ProductsBindingSource.EndEdit()
.CategoriesBindingSource.EndEdit()
.ProductCategories.UpdateDataSet(ProductCategoriesDataSet)
.ProductCategoriesDataSet.AcceptChanges()
Catch ex As Exception
MessageBox.Show("Unable to complete changes. " & ex.Message, "Save", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End If
End With
End Sub
Private Sub ProductDataGridView_CellValidating(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) _
Handles ProductDataGridView.CellValidating
'validate when the user moves to another cell in the same row
With Me.ProductDataGridView
'Dont validate if the form is closing
If Not ClosingBoolean Then
'check for valid product ID
If .Columns(e.ColumnIndex).Name = "ProductID" Then
Dim EnteredDate As Date
If Not Date.TryParse( _
e.FormattedValue.ToString, EnteredDate) Then
ShowCellError(.CurrentCell, _
"Product ID must be entered in a valid format.")
e.Cancel = True
Else
ClearCellError(.CurrentCell)
End If
ElseIf e.FormattedValue.ToString = String.Empty Then
ShowCellError(.CurrentCell, "Entry Needed.")
e.Cancel = True
Else
ClearCellError(.CurrentCell)
End If
End If
End With
End Sub
Private Sub ShowCellError(ByVal CurrentCell As DataGridViewCell, _
ByVal MessageString As String)
'Displays a message if there is an error in the cell
CurrentCell.ErrorText = MessageString
Me.ProductDataGridView.ShowCellErrors = True
End Sub
Private Sub ClearCellError(ByVal CurrentCell As DataGridViewCell)
'Clear previous error messages displayed in the current cell
CurrentCell.ErrorText = String.Empty
Me.ProductDataGridView.ShowCellErrors = False
End Sub
Private Sub ProductDataGridView_DataError(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) _
Handles ProductDataGridView.DataError
'Allow an add to be cancelled
Dim CurrentRow As DataGridViewRow = ProductDataGridView.Rows(e.RowIndex)
If CurrentRow.Cells(0).Value Is DBNull.Value Then
ProductsBindingSource.CancelEdit()
End If
End Sub
Private Sub ProductsBindingSource_DataError(ByVal sender As Object, _
ByVal e As System.Windows.Forms.BindingManagerDataErrorEventArgs) _ Handles ProductsBindingSource.DataError
'Allow a user to cancel a requested add
If ProductDataGridView.CurrentRow.Cells(0) Is DBNull.Value Then
ProductsBindingSource.CancelEdit()
End If
End Sub
'Validate grid data
Private Sub ProductDataGridView_KeyUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles ProductDataGridView.KeyUp
'Check to see if Esc key was pressed in the grid
'Needed to quit an add action
If e.KeyData = Keys.Escape Then
Me.ProductsBindingSource.CancelEdit()
With Me.ProductDataGridView
.ShowCellErrors = False
.ShowRowErrors = False
End With
End If
End Sub
Private Sub ProductDataGridView_RowValidating(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) _ Handles ProductDataGridView.RowValidating
'Validate moves to another row
Dim ErrorFoundBoolean As Boolean = False
Dim MessageString As String
With Me.ProductDataGridView
'Skip validation if the form is closing
If Not ClosingBoolean Then
Dim CurrentRow As DataGridViewRow = .Rows(e.RowIndex)
'Walk through the rows
For Each CheckCell As DataGridViewCell In CurrentRow.Cells
If .Columns(CheckCell.ColumnIndex).Name = "hire_date" Then
Dim TestDate As Date
If Not Date.TryParse(CheckCell.FormattedValue, TestDate) Then
MessageString = "Invalid date format for Date Hired."
ShowRowError(CheckCell, MessageString)
ErrorFoundBoolean = True
End If
ElseIf CheckCell.FormattedValue.ToString = String.Empty Then
'Every Column must have an entry
Dim ColumnHeaderText As String = _
.Columns(CheckCell.ColumnIndex).HeaderText
MessageString = ColumnHeaderText & " is a required entry."
ShowRowError(CheckCell, MessageString)
ErrorFoundBoolean = True
Exit For
End If
Next
If ErrorFoundBoolean Then
e.Cancel = True
Else
ClearRowError(CurrentRow.Cells(0))
End If
End If
End With
End Sub
Private Sub ShowRowError(ByVal CurrentCell As DataGridViewCell, _
ByVal MessageString As String)
'Display a message for the row in error
With Me.ProductDataGridView
.Rows(CurrentCell.RowIndex).ErrorText = MessageString
.ShowRowErrors = True
End With
End Sub
Private Sub ClearRowError(ByVal CurrentCell As DataGridViewCell)
'Clear messages following delivery
With Me.ProductDataGridView
.Rows(CurrentCell.RowIndex).ErrorText = String.Empty
.ShowRowErrors = False
End With
End Sub
Private Sub CategoryTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CategoryTextBox.TextChanged
End Sub
End Class
Upvotes: 0
Views: 500
Reputation: 5269
The DataSource property of a BindingSource object is not suppose to be himself. It's suppose to be the object to use for your binding (object / list / observable collection / etc).
With CategoriesBindingSource
.DataSource = CategoriesBindingSource '<--- Here
.DataMember = "ProductsToCategories"
End With
For example, if you have a person class, you would have something like this:
Dim bob as New Person
With PersonBindingSource
.DataSource = bob
.DataMember = "FirstName"
End With
Here's more infos about the DataSource property:
http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.datasource.aspx
Upvotes: 1