添加新行后如何刷新gridview?

时间:2016-03-22 08:40:01

标签: vb.net winforms gridview devexpress

我做了几项研究,但无法弄清楚问题。我可以在代码中添加,删除或编辑数据库中的行。但是,我无法刷新网格。 我的意思是,当我向gridview添加新行时,它不会出现在gridview中。我重新编译代码后,它出现了。如何刷新gridview?

        Dim strSQL = "SELECT * FROM FIXEDCARD WHERE STKCODE = '" & TextEdit1.Text & "'"
    objCon.Close()
    Dim sqlCmd As New SqlCommand(strSQL, objCon)
    objCon.Open()
    Dim dreader As SqlDataReader
    dreader = sqlCmd.ExecuteReader


    If dreader.Read Then
        'Dim stk_ As String = dreader.GetString(dreader.GetOrdinal("STKCODE")).ToString()
        DevExpress.XtraEditors.XtraMessageBox.Show("already exists", "Info!", MessageBoxButtons.OK)
        objCon.Close()

    Else
        dreader.Close()

        strSQL = "INSERT INTO FIXEDCARD(STKCODE, STKEXP, AUTHCODE, GRPCODE, SPECODE" & _
                                ", SPECODE2, SPECODE3, SPECODE4, SPECODE5, AMORTRATIO, AMORT," & _
                                "PURCH, SALES, RETUR, UNIT) VALUES('" & TextEdit1.Text & "'," & _
                                "'" & TextEdit2.Text & "', '" & TextEdit3.Text & "'," & _
                                "'" & TextEdit4.Text & "', '" & TextEdit5.Text & "'," & _
                                "'" & TextEdit6.Text & "', '" & TextEdit7.Text & "'," & _
                                "'" & TextEdit8.Text & "', '" & TextEdit9.Text & "'," & _
                                "'" & TextEdit10.Text & "', '" & TextEdit11.Text & "'," & _
                                "'" & TextEdit12.Text & "', '" & TextEdit13.Text & "'," & _
                                "'" & TextEdit14.Text & "', '" & TextEdit15.Text & "') "

        sqlCmd = New SqlCommand(strSQL, objCon)
        sqlCmd.ExecuteNonQuery()
        objCon.Close()
    End If

RefreshGrid()         Me.Close()

此外,我尝试编写一个刷新函数,当我将每个按钮调用时,它将刷新gridview。但是,我一直犯了一个错误但却无法识别它。

    Public Sub RefreshGrid()
    Dim T As New DataTable
    Dim strSQL = "Select * From FIXEDCARD"
    Dim sqlCmd As New SqlCommand(strSQL, objCon)
    T = CType(sqlCmd.ExecuteNonQuery(), System.Data.DataTable)
    GridView1.DataSource = T
End Sub

2 个答案:

答案 0 :(得分:0)

您正在使用"非查询"在刷新。这不会返回表值。

尝试使用SqlCommand.ExecuteReader方法。

参考:https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx

答案 1 :(得分:0)

 Public Function FillDataSet(query As String, ByVal ParamArray para() As Object) As DataTable

         dim _transaction As SqlTransaction
         Dim _command As SqlCommand

        _command = New SqlCommand(query, yourConnection)

        _ds = New DataSet
        _sqlda = New SqlDataAdapter(_command )
        _command.Transaction = _transaction

        For i = 0 To para.Count - 1
            _command.Parameters.AddWithValue("@" & i, para(i))
        Next

        _sqlda.Fill(_ds)

       return _ds.tables(0)

  End Function

称之为

  GridControl1.datasource = Nothing
  GridControl1.datasource = FillDataSet(YourInsertQuery,YourParam)
  GridControl1.RefreshDataSource()