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);
                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);


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);

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

This article has been dead for over six months. Start a new discussion instead.