Home » Applications » VB.NET – add record in code behind

VB.NET – add record in code behind

MyForm.aspx

 
<asp:TextBox ID="AddRec" runat="server"> </asp:TextBox> 
<asp:Button ID="AddBtn" runat="server" Text="Add" /> 
<asp:Label ID="LblMsg" runat="server"> </asp:Label> 

MyForm.aspx.vb


Protected Sub AddBtn_Click(sender As Object, e As System.EventArgs) 
                                                   Handles AddBtn.Click
    Dim NewRec As TextBox
    'binding controls
    NewRec = AddBtn.FindControl("AddRec")
              
    If NewLoc.Text.ToString() <> "" Then
    '/ access db connection - 
    '/ MS Access 2007/10 driver * you can define your own sql connection
    Dim Conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;
                                  Data Source=" & Server.MapPath("/MyDB.accdb"))
    Dim cmd As OleDbCommand
        Try
        '/ open connection
           Conn.Open()

         Dim id As String = String.Empty '/ we only in update sql statement
         Dim sql As String
         sql = "INSERET INTO table1 ([location]) VALUES (@NewRec);"
         '* NOTE - misspelled sql statement on purpose | please CORRECT IT
        
         cmd = New OleDbCommand(sql, Conn)
         cmd.Parameters.AddWithValue("@NewLoc", NewLoc.Text.ToString)
         cmd.ExecuteNonQuery()
         Conn.Close()
         '/ end
             '/ redirect page
              Response.Redirect("MyForm.aspx")
             '/ or display confirmation message
             '/ LblMsg.Text = "Input received - thank you!"
        
         '/ catching the exception or error of some kind
            Catch ex As Exception
               '/ display error message
                LblMsg.Text = "ERROR: " & ex.Message.ToString() & ""

            End Try
            
        Else
            '/ validate form control input
            LblMsg.Text = "Required!"
        End If
    End Sub