0

I have a SQL Table [dbo].[Cashiers] ( Cashier_ID int Primary key Identity, Cashier_Name Nvarchar(max) )

now I Loaded the data in this table to a 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

I Created Two Global Variables

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

and I have a Text box and a Button to insert records

    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

All of this is working just fine my problem is that I cant figure out how to show my newly inserted rows in my Datagridview , I was hoping if anyone could provide me with a code snippet or anything that would explain the concept to me , the only think that's working for me right now is to just load a whole new datatable with the new records and just set it as a new datasource for my datagrid view and am sure its not done this way .

thanks in advance.

Willy
  • 3,506
  • 3
  • 22
  • 35
  • You could put the code to load the grid in a seperate function (ex LoadGrid) and call this after inserting. – Saragis Jul 23 '15 at 21:10
  • yea that's what am doing right now , but isn't there any other way to do it ? – Willy Jul 23 '15 at 21:18
  • Well, you're always going to have to retrieve the new row from the database, I don't think there's a way around that. – Saragis Jul 23 '15 at 21:35
  • you can try adding the row programmatically http://stackoverflow.com/questions/10063770/how-to-add-a-new-row-to-datagridview-programmatically – JamieD77 Jul 23 '15 at 21:40

0 Answers0