Petras
Petras

Reputation: 4759

How do you access SQL and display Chinese characters in ASP.NET?

I have a database that stores Chinese characters. This works fine. The code for this system is written in vbscript ASP. Here is a sample http://www.arrb.com.au/test.asp

enter image description here

I also access this database via ASP.NET but the characters do not come out in Chinese.

See here http://www.arrb.com.au/Test-Page.aspx

enter image description here

Why does ASP work and ASP.NET not work?

The code to access the Chinese in ASP.NET is similar to:

query = "select * from myTable ....";

SqlDataAdapter da = new SqlDataAdapter(query, Yart.SQLServerConnections.SqlConnection);
DataSet ds = new DataSet();
da.Fill(ds, "paragraphs");

Response.Write((string)ds.Tables["paragraphs"].Rows[0]["chinese"]);

I am thinking it might be my cast to a string that is destroying the encoding perhaps?

Note that in both sample pages I have this tag:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Upvotes: 0

Views: 3829

Answers (3)

Petras
Petras

Reputation: 4759

The answers above helped, here is how to do it...

There are a lot of articles about this on the net:

http://csharpindepth.com/Articles/General/Strings.aspx

http://www.joelonsoftware.com/articles/Unicode.html

But suffice to say this. When you save characters from a form postback the characters will be encoded. If you do not specify an encoding it will be determined for you.

This can be very confusing!

Chinese characters may appear to look OK in ASP but not in ASP.NET

So to stop problems, always declare your encodings! Typically we use utf-8.

In ASP, do this:

<% @CodePage = 65001 %>
<%Option Explicit%>

<%
Session.CodePage = 65001 
Response.CodePage = 65001
Response.CharSet = "utf-8" 
%>

When saving SQL directly, make sure the characters get saved in nvarchar, ntext etc Make sure the SQL statement has the N character

update [someTable] set [col]=N'...'

Declare the encoding in HTML as well:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

In ASP.NET, add this to web.config:

<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
fileEncoding="utf-8"/>

Upvotes: 1

Naraen
Naraen

Reputation: 3250

What encoding was used when saving the data to the database? Try converting your string to use the same encoding before doing a Response.Write.

List of encodings available here ... http://msdn.microsoft.com/en-us/library/system.text.encoding(v=VS.100).aspx

Here is the method to use for converting to the right type http://msdn.microsoft.com/en-us/library/kdcak6ye.aspx

Upvotes: 1

Predator
Predator

Reputation: 1275

Maybe this class can help you:

System.Text.UTF8Encoding

Upvotes: 0

Related Questions