无法弄清楚如何向Datagrid视图显示新插入的行

时间:2015-07-23 20:59:22

标签: sql-server vb.net

我有一个SQL表[dbo]。[收银员] ( Cashier_ID int主键标识, Cashier_Name Nvarchar(最大) )

现在我将此表中的数据加载到Datatable In VB.Net

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Using conn As New SqlConnection(My.Settings.Lol)
        Try
            Dim Adp As New SqlDataAdapter

            With Adp
                .SelectCommand = New SqlCommand("SELECT * FROM [dbo].[Cashiers]", conn)
                .Fill(DT)
            End With
            BS.DataSource = DT
            DataGridView1.DataSource = BS

            Adp.Dispose()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        Finally
            conn.Close()
        End Try
    End Using
End Sub

我创建了两个全局变量

Dim DT As New DataTable 'Global Variable
Dim BS As New BindingSource 'Global Variable

我有一个文本框和一个用于插入记录的按钮

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using conn As New SqlConnection(My.Settings.Lol)
        Dim cmd As New SqlCommand
        With cmd
            .CommandText = "INSERT INTO [dbo].[Cashiers] ([Casheir_Name]) VALUES (@Cashier_Name)"
            .Connection = conn
            .Parameters.Add("@Cashier_Name", SqlDbType.VarChar).Value = TextBox1.Text.Trim
        End With
        Try
            conn.Open()
            cmd.ExecuteNonQuery()

            cmd.Dispose()
            TextBox1.Text = Nothing
            MsgBox("Added!")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        Finally
            conn.Close()
        End Try
    End Using
End Sub

所有这一切都工作正常我的问题是我无法弄清楚如何在我的Datagridview中显示我新插入的行,我希望是否有人可以提供我的代码片段或任何可以向我解释这个概念的内容,现在唯一认为对我有用的就是用新记录加载一个全新的数据表,并将其设置为我的数据网格视图的新数据源,并确定它不是这样做的。

提前感谢。

0 个答案:

没有答案