你好, 因此,這是一個家庭作業,並在很短的教練放棄了我。當我運行我的程序時,我收到此錯誤消息。我試着對這個綁定的代碼行進行註釋,當我運行這個程序時,它給了我下一個綁定(大約三行下)的同樣的錯誤。
我把程序發給了我的老師,他說程序運行了,但是我的表單沒有正確加載或訪問數據庫,這是我看不到的,因爲每次運行這個程序時我都會得到這個錯誤。
這個任務已經過期了,我只需要一個輪盤,但更重要的是,我真的很煩,他沒有試圖幫助我。他的迴應只是「我看不到錯誤」,即使在我給他發送屏幕截圖之後。我真的很想弄清楚什麼是錯的。我想知道它是否是我的機器,因爲它似乎只發生在我的機器上?如果有,我應該更新什麼?我將如何檢查?因爲這個,我不想失敗任何其他任務。
這裏是我的數據庫代碼的副本:
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
這裏是表單代碼的副本:
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Ë作爲System.Windows.Forms.BindingManagerDataErrorEventArgs)_ 把手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 Sy stem.Windows.Forms.DataGridViewCellCancelEventArgs)_ 把手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
謝謝你分享鏈接並解釋我出錯的地方。我會給這個鏡頭,但我認爲這是朝着正確的方向邁出的一步,肯定比我從教練那裏得到的幫助更多,而且我不必向你付學費! –