Stan Overby
Stan Overby

Reputation: 43

Multiple parameters taking up multiple lines in C#

I am trying to develop a C# windows form application using visual studio. It connects to a microsoft access database. I have a form that saves data to the database. I have text boxes that I need to link to the database field. My problem is I have a lot of textbox names and values for the textbox to code so I need to do it on multiple lines. I did a search on this site and I see you can use the @ symbol in front of the first set of double quotes which encases the first group of parameters but I am not sure how to deal withe the second group of parameters which is the list of values. It would be something like:

command.CommandText = @"insert into xxx (xx,xx,xx,xx,xx,xx,xx)

but when it gets to

values('" + txt_ID.Text + "','" + txt_Nickname.Text + "')"

I get an error saying

"newline in constant"

and that it expects either a ";" or a "}".

So basically I have to set of parameters that I am trying to code on multiple lines.

Upvotes: 1

Views: 659

Answers (1)

Arthur Rey
Arthur Rey

Reputation: 3056

You should use parameterized queries:

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (@id, @nickname)";

OleDbParameter[] parameters = new OleDbParameter[2];
parameters[0] = new OleDbParameter("@id", Convert.ToInt32(txt_ID.Text));
parameters[1] = new OleDbParameter("@nickname", txt_Nickname.Text);

command.Parameters.AddRange(parameters);

Keep in mind that the parameters must be added in the same order they appear in the query. OleDb doesn't use the names but only the order.

That is why you could use "?" as placeholders in the query with the exact same result

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (?, ?)";

Upvotes: 4

Related Questions