Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
What is wrong with this code, because i can't insert data to my service-based DB. DB connect is OK so something must be wrong with code next from the end ofthe catch syntax

C#
string cn=@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
            SqlConnection connection = new SqlConnection(cn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommand command = new SqlCommand();
            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("ERROR");
                connection.Close();
            
            }
            command = new SqlCommand("SELECT * FROM users",connection);
            adapter.SelectCommand = command;
            command = new SqlCommand("INSERT INTO users(uname,pass,mail)"+
            "VALUES(@uname,@pass,@mail)",connection);
            //
            command.Parameters.Add("@uname", tBuime.Text);
            command.Parameters.Add("@pass", tBgeslo.Text);
            command.Parameters.Add("@mail", tBeposta.Text);
            //
            adapter.InsertCommand = command;
            connection.Close();



Thanx for help !
Posted
Updated 12-Feb-12 22:01pm
v2
Comments
Al Moje 13-Feb-12 4:02am    
Added pre tag.

You do not need the adapter. Just do a
C#
command.ExecuteNonQuery();
 
Share this answer
 
Use this code

C#
command.Parameters.Add("@uname", tBuime.Text);
            command.Parameters.Add("@pass", tBgeslo.Text);
            command.Parameters.Add("@mail", tBeposta.Text);
            //
            adapter.InsertCommand = command;
            //added line  
            adapter.InsertCommand.ExecuteNonQuery();
            //added line ENDS HERE 
            connection.Close();


Hope this will help you if it works fine then accept this answer
Thanks...
 
Share this answer
 
You have to call
C#
adapter.Update

method to execute the insert command before closing the connection
 
Share this answer
 
Comments
ProEnggSoft 13-Feb-12 4:30am    
Can you please tell me the reason for down voting

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