I am trying to store a value from a selected row from one table into another. My code is as follows.

 string CustomerID = textBox1.Text;


                SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
                con1.Open();
                SqlCommand myCommand = new SqlCommand("Select CustomerID, Name from TableCustomer WHERE (CustomerID like '" + CustomerID+ "')", con1);

                SqlDataReader rdr = myCommand.ExecuteReader();

                    while (rdr.Read())
                    {
                        string Name = rdr["Name"].ToString();

                    }           
                SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber, CustomerName) VALUES
                (@CustomerID,   @Name )", con);
                cmd.ExecuteNonQuery();

                con1.Close();

My code is not working properly. All is I want to insert Name and ID of customer in Name field of finalTable. What is wrong with this code?

First of all, if you have an CustomerId, you should use equals instead of like. If you use Like you can ending with the wrong customer.
Like this:

WHERE (CustomerID = '" + CustomerID+ "')

Now for the part that doesn't work. On your second query you are not setting the CustomerId nor the Name on your sql string. And you're also using a connection named con that doesn't exists.

You could try like this:

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber, CustomerName) VALUES ('" + CustomerId + "', '" + Name + "' )", con1);
cmd.ExecuteNonQuery();

Or you could use a more elegant way with SQL Parameters: http://www.dotnetperls.com/sqlparameter

thankyou dear it worked for me...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.