数据不会在运行时显示在DataGridView中

时间:2016-04-01 08:08:09

标签: .net vb.net datagridview

我已经编写了一些代码行来使用保存按钮向我的数据库添加/保存数据,但每次运行程序并将数据输入到各种文本框中时,我只看到一个对话框“记录成功保存”但是我的datagridview中没有显示任何内容,我已经检查了各种站点的帮助,似乎非工作,有些人可以帮我看一下我的代码行,我还是vb的新手。我正在使用sql server compact 3.5,我的数据表是“treatment_price”。

 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try
            Dim Query As String

            'Query ="INSERT INTO Treatment_price"
            Dim con As SqlServerCe.SqlCeConnection = New SqlServerCe.SqlCeConnection("Data Source= C:\Users\Chinedu\Documents\Visual Studio 2010\Projects\GUU Specialist Hospital 1\GUU Specialist Hospital 1\Treatment_price_unit.sdf")
            Dim sql As SqlCeCommand = New SqlCeCommand("Query", con)

            Query = " INSERT INTO Treatment_price(Patient_Name, " & "Patient Address, Admitted Date,Patients Date Of Birth,Blood Group_Genotype,Treatment1,Treament2,Treament3,Trement4,Treament5,Treament6,Unit_Price1,Unite_Price2,Unit_Price3,Unite_Price4,Unit_Price5,Unit_Price6,SubTotal,Tax,Total)VALUES('" & Patient_NameTextBox.Text & "','" & Patient_AddressTextBox.Text & "','" & Treatment1TextBox.Text & "','" & Treatment2TextBox.Text & "','" & Treatment4TextBox.Text & "','" & Treatment5TextBox.Text & "','" & Treatment6TextBox.Text & "','" & Unit_Price1TextBox.Text & "','" & Unit_Price2TextBox.Text & "','" & Unit_Price3TextBox.Text & "','" & Unit_Price4TextBox.Text & "','" & Unit_Price5TextBox.Text & "','" & Unit_Price6TextBox.Text & "','" & SubTotalTextBox.Text & "','" & TaxTextBox.Text & "','" & TotalTextBox.Text & "');"
            con.Open()
            Dim cmd As SqlServerCe.SqlCeCommand = New SqlServerCe.SqlCeCommand(Query, con)
            cmd.ExecuteNonQuery()
        Catch
            If MsgBox("Record is Successfully Inserted") Then
            Else
                MsgBox("Record Not Succesfully Inserted,Please Check Missing Fields")
            End If
            con.Close()
        End Try


    End Sub

2 个答案:

答案 0 :(得分:0)

好的,我不知道你的错误,但是你以错误的方式处理异常。这是你应该怎么做(更不用说这里的SQL注入):

Try
  ' Your code here
Catch e as Exception
  MsgBox.show(e.Message, "An Error occured")
End Try

注意:我在这里发帖是因为它太过于评论......

答案 1 :(得分:0)

试试这个:

' Assumes that connection is a valid SqlConnection object.

   'your query
   Dim queryString As String = _
   "SELECT Patient_Name,Patient_Address,AdmittedDate,PatientsDateOf Birth,Blood Group_Genotype,Treatment1,Treament2,Treament3,Trement4,Treament5,Treament6,Unit_Price1,Unite_Price2,Unit_Price3,Unite_Price4,Unit_Price5,Unit_Price6,SubTotal,Tax,Total FROM dbo.Treatment_price"

   Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
   queryString, connection)

   Dim dsTreatment_price As DataSet = New DataSet
   adapter.Fill(dsTreatment_price)

   'fill grid
   datagridview1.dataSource = dsTreatment_price.tables(0) 

SqlDataAdapter Class