我已經創建了一個測試項目,簡單地通過使用存儲過程使DataGridView與Sql Server一起工作。我關注Employee類中的所有SQL Server機制,以及frmMain表單上的datagridview活動。如何使用VB.NET將DataAdapter配置爲使用Sql Server存儲過程進行選擇,更新,插入和刪除命令?
本質上,我將在所有四個命令中使用一些相同的列。
我想定義每個參數一次,然後將其添加到所有需要它的命令。問題是,我收到錯誤「SqlParameter已被另一個SqlParameterCollection包含」。有人告訴我,我將不得不爲每個使用它的命令命名每個參數。我可以看到這將如何,但我希望有人在那裏知道如何使單列一參數方法的工作。
Employee Class
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Public Class Employees
'Declarations
Private dtEmployees As DataTable
Private daEmployeer As SqlDataAdapter
Const HotmixCn As String = "Data Source=MyServer;Initial Catalog=MyDatabase;User ID=USER;Password=password"
Private Cn As SqlConnection
'Properties
Public Property EmployeeList As DataTable
Get
Return dtEmployees
End Get
Set(value As DataTable)
dtEmployees = value
End Set
End Property
'Methods
Public Sub New()
' Try
Cn = New SqlConnection(HotmixCn)
daEmployeer = New SqlDataAdapter
Dim cmdSelectEmployees As New SqlCommand
Dim cmdInsertEmployee As New SqlCommand
Dim cmdUpdateEmployee As New SqlCommand
Dim cmdDeleteEmployee As New SqlCommand
'Configure the Select command (!! have to for SP)
With cmdSelectEmployees
.CommandType = CommandType.StoredProcedure
.CommandText = "uspTestGetEmployees"
.Connection = Cn
End With
--- Same thing for Insert, Update and Delete
'
'/// Add The Parameters To All Three Commands ///
Dim parm As SqlParameter
parm = New SqlParameter
With parm
.ParameterName = "@EmpNo"
.SqlDbType = SqlDbType.Int
.Direction = ParameterDirection.Input
.SourceColumn = "EmpNo"
End With
cmdInsertEmployee.Parameters.Add(parm)
cmdUpdateEmployee.Parameters.Add(parm)
'cmdDeleteEmployee.Parameters.Add(parm)
'
----- Similar for remaining parameters
'
'Include the individual commands in the dataadapter
daEmployeer.SelectCommand = cmdSelectEmployees
daEmployeer.UpdateCommand = cmdUpdateEmployee
daEmployeer.InsertCommand = cmdInsertEmployee
daEmployeer.DeleteCommand = cmdDeleteEmployee
'/// Fill the Datatable
dtEmployees = New DataTable
Cn.Open()
daEmployeer.Fill(dtEmployees)
Cn.Close()
'Catch ex As Exception
'MsgBox(ex.Message)
'End Try
End Sub
'Events
End Class
這是很少的代碼與在DataGridView雲:
Imports DataLayer
Public Class frmMain
Dim emp As New Employees
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dgvEmployees.DataSource = emp.EmployeeList
End Sub
End Class
代碼太多......嘗試將其剝離爲一個非常基本的示例,以獲得對您的問題更多的興趣。 – Tanner 2014-09-24 15:46:43