yash fale
yash fale

Reputation: 331

how to insert newline after word in sql table in c#

I am trying to insert New Line after word car but it is not working with folowing solution

  1. Char(13) - not working
  2. Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
  3. \n\r - not working

Code:

cmd.Parameters.AddWithValue("@ColumnCar", Car + "char(13)" + "Rate:2CR"; 
  //cmd.Parameters.AddWithValue("@ColumnCar", Car + "\n\r" + "Rate:2CR"; 
  //cmd.Parameters.AddWithValue("@ColumnCar", Car + Environment.NewLine + "Rate:2CR"; 

cmd.ExecuteNonQuery(); 

Need output in sql table ColumnCar row value as follows:

Car
Rate:2cr  

Note : here after Car there will be a newline and then Rate:2Cr will be added

Upvotes: 4

Views: 8502

Answers (4)

user1562155
user1562155

Reputation:

The following code works fine with unicode fields in a MS SQL-Server 2016 DB :

  string carString = $"Volvo{Environment.NewLine}Rate: 2CR";

  SqlParameter parameter = new SqlParameter("@ColumnCar", carString);
  command.Parameters.Add(parameter);

The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?

Don't use string1 + " " + string2 concatenation. Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.

Upvotes: 0

Igor
Igor

Reputation: 62308

With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.

Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As @mhasan pointed out it could also be different depending on the O/S.

Using characters

const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;

var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("@ColumnCar", toInsert);

This would also work and produce the same result:

var toInsert = car + "\n" + "Rate:2CR";

Upvotes: 2

vijay chaudhary
vijay chaudhary

Reputation: 39

Try this code hope its working...

Make a string variable and store all value in variable..

ex: string abc=textbox1.text+" "+"Rate:2cr"; @ColumnCar=abc.tostring();

now put your code

cmd.Parameters.AddWithValue("@ColumnCar",datatype); cmd.executenonquery();

Upvotes: 0

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system. For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.

Upvotes: 1

Related Questions