stefan
stefan

Reputation: 439

inserting multiple values from C# into one row in a SQL table

I have a table which i want to store all the outputs into one row seperated by a space(eg "textbox1 textbox2 textbox3". How would i do this? At the moment its trying to put them into different columns. Giving me an error stating im using fewer columns.

            }
            using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (@textbox1, @textbox2, @textbox3)", cn))
            {
                cmd.Parameters.AddWithValue("@textbox1", textBox1.Text);
                cmd.Parameters.AddWithValue("@textbox2", textBox2.Text);
                cmd.Parameters.AddWithValue("@textbox3", textBox3.Text);
                cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery() 
                MessageBox.Show("Success!");

            }
        }

Upvotes: 0

Views: 3471

Answers (2)

Akash KC
Akash KC

Reputation: 16310

You are inserting data in more column than you have specified so I think you have got the error in that part. So, make some modification in code to remove the error:

   }
            using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (@textbox1+' '+ @textbox2+' '+ @textbox3)", cn))
            {
                cmd.Parameters.AddWithValue("@textbox1", textBox1.Text);
                cmd.Parameters.AddWithValue("@textbox2", textBox2.Text);
                cmd.Parameters.AddWithValue("@textbox3", textBox3.Text);
                cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery() 
                MessageBox.Show("Success!");

        }
    }

Upvotes: 1

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Try this:

using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (@text)", cn))
            {
                cmd.Parameters.AddWithValue("@text", textBox1.Text + " " + textBox2.Text + " " + textBox3.Text);

                cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery() 
                MessageBox.Show("Success!");

            }

Upvotes: 2

Related Questions