参数异常错误,不知道该怎么做

时间:2013-10-19 02:07:15

标签: vb.net exception arguments

enter image description here

你好 所以这是一个家庭作业,简而言之,教练放弃了我。当我运行我的程序时,我收到此错误消息。我试着注释掉那个绑定的代码行,当我运行程序时,它在下一次绑定时给了我同样的错误(大约三行)。

我把程序发送给我的老师,他说程序运行但我的表单没有正确加载或访问数据库,这是我无法看到的,因为每次运行此程序时都会出现此错误。

这项任务已经过期了,我只需要进行一次调度,但更重要的是,我真的很生气,因为他并没有试图帮助我。即使在我发给他屏幕截图之后,他的回答只是“我没有看到错误”。我真的想弄明白什么是错的。我想知道它是不是我的机器,因为它似乎只发生在我的机器上?如果有,我应该更新一些东西?我该怎么检查?因此,我不想让任何其他任务失败。

以下是我的数据库代码的副本:

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 e As 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 System.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

1 个答案:

答案 0 :(得分:1)

BindingSource对象的DataSource属性不应该是他自己。它被认为是用于绑定的对象(对象/列表/可观察集合/等)。

    With CategoriesBindingSource
        .DataSource = CategoriesBindingSource  '<--- Here
        .DataMember = "ProductsToCategories"
    End With

例如,如果你有一个人类,你会有这样的东西:

Dim bob as New Person

With PersonBindingSource
    .DataSource = bob
    .DataMember = "FirstName"
End With

以下是有关DataSource属性的更多信息:

http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.datasource.aspx