2014-10-28 43 views
0

我有1個DataGridView有3列,1個按鈕名爲AssignID,1有數據庫EmployeeList表。的DataGridView在Datagridview中自動分配員工號碼

  1. 列1 =僱員
  2. 列2 = EmployeeName
  3. 列3 =部門

我粘貼EmployeeName部的數據將excel中的轉換爲DataGridView,並將第1列留作空白。我的問題是,當我按下按鈕AssignID時,如何在DataGridView中自動分配每個員工的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

我對你的問題有點困惑。你是否想要如何在datagridview單元格中找到合適的人? – Kat 2014-10-28 19:48:41

回答

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 
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,你將有一個DataTable假設只有1行與您的要求爲內容的員工。通過在DataGridView的每一行

Dim empID as integer = DT.rows(0).item("<name of SQL column with employee ID>") 

然後你循環,並尋找合適的行具有要改變員工:然後你就可以抓住的價值,像這樣。

NewEmployeesDataGridview.Rows(<integer of row>).Cells(<integer of column with IDs>).Value = empID 

這只是一種方法。您可以找到該員工的行,並將其分配給for循環中的適當單元格。或者使用LINQ,如果你願意,可以使用distinct()來更快地找到它。

+0

現在工作。非常感謝Aprendiendo.NET! – 2014-10-29 03:51:17