更新Datagridview?

时间:2015-01-02 09:39:12

标签: vb.net datagridview

我试图弄清楚如何更新DataGridView中的选定行。我希望我的系统能够识别我从datagridview中选择的现有信息行(我已将其设置为完整行选择btw)并通过更改文本框和组合框来更新/编辑信息用来添加它们。我的表中的所有内容都设置为Text数据类型,ID除了是自动编号。但是,我在下面使用的代码中出错。任何帮助将不胜感激!谢谢:)(我将提供错误屏幕截图的链接,因为我没有足够的声誉。) *我用括号括起部分时出现新错误 http://i.imgur.com/gs8rVhB.png

Imports System.Data.OleDb

Public Class AdmMain

Dim con As New OleDbConnection

Sub fillcombo()
    strsql = " select yrgr from yearandgrade"
    Dim acscmd As New OleDb.OleDbCommand
    acscmd.CommandText = strsql
    acscmd.Connection = acsconn
    acsdr = acscmd.ExecuteReader

    While (acsdr.Read())
        cboyr.Items.Add(acsdr("yrgr"))
    End While
    acscmd.Dispose()
    acsdr.Close()
End Sub

Sub comb2()
    strsql = " select sections from sectio"
    Dim acscmd As New OleDb.OleDbCommand
    acscmd.CommandText = strsql
    acscmd.Connection = acsconn
    acsdr = acscmd.ExecuteReader

    While (acsdr.Read())
        cbosec.Items.Add(acsdr("sections"))
    End While
    acscmd.Dispose()
    acsdr.Close()
End Sub

Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
    If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
        MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
        Me.Close()
        LoginUser.Show()
    End If
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Me.TxtID.Text = ""
    Me.txtFName.Text = ""
    Me.txtMName.Text = ""
    Me.txtLName.Text = ""
    Me.cboyr.Text = ""
    Me.cbosec.Text = ""
    Me.TxtID.Focus()
End Sub

Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Module1.connect()
    Me.fillcombo()
    Me.comb2()


    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Thesis\Thesis\Database1.accdb"

    con.Open()

    datagridshow()
End Sub

Private Sub datagridshow()
    Dim ds As New DataSet
    Dim dt As New DataTable
    ds.Tables.Add(dt)
    Dim da As New OleDbDataAdapter

    da = New OleDbDataAdapter("select * from students ", con)
    da.Fill(dt)

    DataGridView1.DataSource = dt.DefaultView

    con.Close()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
    Dim rbdtext As String = cboyr.SelectedItem.ToString
    Dim uno As String = cbosec.SelectedItem.ToString

    Try
        Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                     "Data Source=C:\Thesis\Thesis\Database1.accdb"
        Dim sqlquery As String = "INSERT INTO students " & _
            "(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
            "VALUES (@studid, @fname,@mname,@lname,@yr, @sec)"

        ' Use this form to initialize both connection and command to 
        ' avoid forgetting to set the appropriate properties....

        Using conn = New System.Data.OleDb.OleDbConnection(cnString)
            Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)

                conn.Open()
                cmd.Parameters.AddWithValue("@studid", TxtID.Text)
                cmd.Parameters.AddWithValue("@fname", txtFName.Text)
                cmd.Parameters.AddWithValue("@mname", txtMName.Text)
                cmd.Parameters.AddWithValue("@lname", txtLName.Text)
                cmd.Parameters.AddWithValue("@yr", rbdtext)
                cmd.Parameters.AddWithValue("@sec", uno)

                If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
                    MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Return
                Else
                    Dim rowsInserted = cmd.ExecuteNonQuery()
                    If rowsInserted > 0 Then
                        MessageBox.Show("One record successfully added!", "Added!")
                        datagridshow()
                    Else
                        MessageBox.Show("Failure to add new record!", "Failure!")
                    End If
                End If

            End Using
        End Using
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Private Sub TxtID_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtID.KeyPress

    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
    Dim rbdtext As String = cboyr.SelectedItem.ToString
    Dim uno As String = cbosec.SelectedItem.ToString

    Try
        Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                     "Data Source=C:\Thesis\Thesis\Database1.accdb"
        Dim sqlquery As String = "UPDATE Students SET StudentID = @STUDID, FirstName = @FNAME, MiddleName = @MNAME, LastName= @LNAME, Yr = @YRR, [Section] = @SEC WHERE StudentID = @STUDID, FirstName =@FNAME, MiddleName = @MNAME, LastName= @LNAME, Yr = @YRR, [Section] = @SEC"



        ' Use this form to initialize both connection and command to 
        ' avoid forgetting to set the appropriate properties....

        Using conn = New System.Data.OleDb.OleDbConnection(cnString)
            Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)

                conn.Open()
                cmd.Parameters.AddWithValue("@STUDID", TxtID.Text)
                cmd.Parameters.AddWithValue("@FNAME", txtFName.Text)
                cmd.Parameters.AddWithValue("@MNAME", txtMName.Text)
                cmd.Parameters.AddWithValue("@LNAME", txtLName.Text)
                cmd.Parameters.AddWithValue("@YRR", rbdtext)
                cmd.Parameters.AddWithValue("@SEC", uno)

                If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
                    MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Return
                Else
                    Dim rowsInserted = cmd.ExecuteNonQuery()
                    If rowsInserted > 0 Then
                        MessageBox.Show("One record successfully updated!", "Updated!")
                        datagridshow()
                    Else
                        MessageBox.Show("Failure to update new record!", "Failure!")
                    End If
                End If

            End Using
        End Using
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

End Class

1 个答案:

答案 0 :(得分:0)

UPDATE ... WHERE表达式的语法需要一个唯一标识要更新的记录的条件。如果条件是由多个字段/值组成的表达式,则应使用AND或OR运算符组合这些条件,而不是使用逗号。

WHERE子句中的条件通常使用表的PRIMARY KEY来标识要更新的记录(在您的情况下,这似乎是StudentID字段),因此您只需要编写

Dim sqlquery As String = "UPDATE Students SET FirstName = @FNAME, " &_ 
                         "MiddleName = @MNAME, LastName= @LNAME, Yr = @YRR, " & _ 
                         "[Section] = @SEC " & _ 
                         "WHERE StudentID = @STUDID"

请注意,如果StudentID是PRIMARYKEY,您不会尝试更改/更新它,因为这可能会导致您与Students表格引用(有关系)的其他数据库表格不一致

最后,OleDb提供程序不会通过其名称识别参数,提供程序期望传递的每个参数与参数占位符在命令文本中出现的顺序相同(它使用参数的位置)将值传递给数据库引擎),因此您还需要更改为UPDATE设置参数集合的顺序

cmd.Parameters.AddWithValue("@FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("@MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("@LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("@YRR", rbdtext)
cmd.Parameters.AddWithValue("@SEC", uno)

cmd.Parameters.AddWithValue("@STUDID", TxtID.Text)