我有1个DataGridView有3列,1个按钮名为 AssignID ,1个数据库有 EmployeeList 表。
Datagridview的列
我将 EmployeeName 和部门的数据从excel粘贴到DataGridView,将第1列留空。我的问题是当我按下按钮 AssignID 时,如何在DataGridView中自动为每个Employee分配 EmployeeID 。数据库中的最后一个 IDNumber 为10000。
感谢您的帮助。我还在学习vb.net。在此先感谢。
我使用下面的代码:
Private Sub AssignID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AssignID.Click
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
Dim query As String
Dim dbup As New OleDbCommand
Try
query = "SELECT Max (EmployeeID) from EmployeeList"
dbup = New OleDbCommand(query, Dbcon)
Dim EmpID As Integer
EmpID = dbup.ExecuteScalar
Dim i2 As Integer
i2 = Me.NewEmployeesDataGridview.CurrentRow.Index
NewEmployeesDataGridview.Item(0, i2).Value() = EmpID
For x As Integer = 0 To NewEmployeesDataGridview.Rows.Count - 2
NewEmployeesDataGridview.Rows(x).Cells(0).Value = NewEmployeesDataGridview.Rows(0).Cells(0).Value + 1
Next
NewEmployeesDataGridview.AllowUserToAddRows = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
答案 0 :(得分:1)
我以前从未使用过这种方法,但我可能会使用datadapter。在数据表和表格中思考起来比较容易。
例如:
Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "<whatever your connection string is>"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
(SELECT Max (EmployeeID) from EmployeeList)
Dim ds As DataSet = New DataSet()
'fill adapter
adp.Fill(ds)
Dim DT as datatable = ds.Tables(0)
因此,在DT中,您将拥有一个数据表,假设只有一行与您请求的员工作为其内容。然后你可以像这样获取值:
Dim empID as integer = DT.rows(0).item("<name of SQL column with employee ID>")
然后循环遍历datagridview中的每一行,并查找包含您要更改的员工的右侧行。
NewEmployeesDataGridview.Rows(<integer of row>).Cells(<integer of column with IDs>).Value = empID
这只是一种方法。您可以找到该员工的行,并将其分配给for循环中的正确单元格。或者使用LINQ,如果你了解它,那么使用distinct()来更快地找到它。
答案 1 :(得分:1)
如果表中最后一个分配的ID是10,000,那么下一个ID是10,000 + 1,即10,001。因此:
EmpID = dbup.ExecuteScalar + 1
'.Note #1: The code that is commented is not necessary
'Dim i2 As Integer
'i2 = Me.NewEmployeesDataGridview.CurrentRow.Index
'
'NewEmployeesDataGridview.Item(0, i2).Value() = EmpID
'.Note #1.
'To Rows.Count - 1 throw the correct result:
NewEmployeesDataGridview.AllowUserToAddRows = False
'For each row in the datagridview, we increase by one each ID from the last ID
For x As Integer = 0 To NewEmployeesDataGridview.Rows.Count - 1
NewEmployeesDataGridview.Rows(x).Cells(0).Value = EmpID + x
Next