【发布时间】:2014-09-24 15:42:23
【问题描述】:
我创建了一个测试项目,它只是通过使用存储过程使 DataGridView 与 Sql Server 一起工作。我负责 Employee 类中的所有 SQL Server 机制,以及窗体 frmMain 上的 datagridview 活动。
本质上,我将在所有四个命令中使用一些相同的列。
我想一次定义每个参数,然后将其添加到所有需要它的命令中。麻烦的是,我收到错误“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
【问题讨论】:
-
代码太多...尝试将其简化为一个非常基本的示例,以便对您的问题产生更多兴趣。
标签: sql-server vb.net stored-procedures datagridview sqldataadapter