Click here to Skip to main content
15,909,030 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Good day every one

please I need help in coding this small easy program

it just three text boxes and one button to save them

this is my code

Imports System.Data
Imports System.Data.SqlClient



Public Class Form1

    Dim cmd As SqlCommand
    Dim con As SqlConnection
   
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ConID As String
        Dim ConAddress As String
        Dim ConPhone As String

        ConID = Me.TextBox1.Text
        ConAddress = Me.TextBox2.Text
        ConPhone = Me.TextBox3.Text
        Try


            con.ConnectionString = "Data Source=DBS;Initial Catalog=Recruitment ;User Id=myuserid;Password=Mypassword"
            con.Open()
            cmd.Connection = con
            cmd.CommandText = "INSERT INTO Contacts(ConID, ConAddress,ConPhone ) VALUES('" & ConID & "' , '" & ConAddress & "' , '" & ConPhone & "') "
        Catch ex As Exception
            MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
        Finally
            con.Close()
        End Try



    End Sub

End Class
Posted

If conID is numeric, you need not enclose it in quotes.
SQL
"INSERT INTO Contacts(ConID, ConAddress,ConPhone ) VALUES(" & ConID & " , '" & ConAddress & "' , '" & ConPhone & "') "

Suggestion: You should use command with parameters or procedures.
 
Share this answer
 
not working :(

it keeps telling me this error

" Error while inserting on table... Object Reference not set to an instance of an object "

what is that mean ?
 
Share this answer
 
Comments
nagendrathecoder 17-Aug-11 8:26am    
Debug your code and tell us exactly on which line it is throwing exception.
omar aslani 17-Aug-11 8:41am    
test.exe!test.Form1.Button1_Click(Object sender, System.EventArgs e) Line 29 Basic
First of all, use parameters in your statement, don't concatenate literals to the SQL text. More info, see: SqlParameter [^]. When you use parameters, you don't have to worry for example about data type conversions etc.

The problem looks like that you define the connection and the command variables but you don't create instances of those classes at all. So try changing to:
VB
Dim con As New SqlConnection
Dim cmd As New SqlCommand


Another thing is that you set the sql statement but based on your code you don't execute it at all. Use ExecuteNonQuery[^] to actually execute the statement
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900