如何将listview项插入3个不同的表VB.net

时间:2015-06-24 01:45:43

标签: vb.net sql-server-2008 listview

我试图建立一个图书馆系统。我有一个listview,它包含要插入到不同表中的项目(b_borrow_tbl,用于书籍,d_borrow_tbl用于多媒体,m_borrow_tbl用于模块)。

我使用此代码将项目插入b_borrow_tbl:

       Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
    selecteduser = cmb_borrower.SelectedValue
    myconnection.Open()

    For xa = 0 To ListView1.Items.Count - 1

        Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(@bid,@user,@dateborrowed,@admin ,'" & "Borrowed" & "')", myconnection)
        mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
        mycommand.Parameters.AddWithValue("user", selecteduser)
        mycommand.Parameters.AddWithValue("dateborrowed", datestring)
        mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
        mycommand.ExecuteNonQuery()
        myconnection.Close()

    Next
    MsgBox("Transaction Saved")

    ListView1.Items.Clear()
    myconnection.Close()

End Sub

1 个答案:

答案 0 :(得分:1)

这是一种可能性。请注意,我无法为您提供准确的代码,因为我不知道您其他表格的结构......所以,请注意......

   Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()

For xa = 0 To ListView1.Items.Count - 1

    Dim itemType as String
    itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #

    if itemType="Books" Then
        Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(@bid,@user,@dateborrowed,@admin ,'" & "Borrowed" & "')", myconnection)
        mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
        mycommand.Parameters.AddWithValue("user", selecteduser)
        mycommand.Parameters.AddWithValue("dateborrowed", datestring)
        mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
        mycommand.ExecuteNonQuery()
    End If

    If itemType="Multimedia" Then
        mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (@parm1,@parm2,...)
        mycommand.Parameters.Clear()
        mycommand.Parameters.AddWithValue("@param1",value)
        ' etc
        mycommand.ExecuteNonQuery()

      ' Then repeat by changing command text for third table
      ' clearing/defining parameters, then executing the query
    End If
    myconnection.Close()

Next
MsgBox("Transaction Saved")

ListView1.Items.Clear()
myconnection.Close()

End Sub

我们在这里做的就是"重置" " mycommand"变量带有新的INSERT语句,清除参数,并为第二次和第三次插入重新定义它们。请注意,在所有三个插入触发之后,连接才会关闭。您显然需要更换"占位符" of" field1,field2"和@ param1,@ param2等一起使用表中的实际字段,但我认为这应该会给你一个正确的方向。