0

I am working on a C# project. I have created a dataset by use of sql server and I tried to show the data in DataGridView table. Then I added a button to change the selected data. when I use English language for editing the data, it works perfectly. But when I change the language, question mark is shown.

to edit the data I use the following commands.

sqlStr = "Update Employee Set FirstName = '" + FirstName.Text + "' Where ID = '" + ID.Text + "'";
        cmd.CommandText = sqlStr;
        cmd.Connection = connect;
        cmd.ExecuteNonQuery();

any help is appreciated. thanks

user42037
  • 39
  • 7
  • Are you sure that your data is in Unicode? Do you use Windows Forms DataGridView? – Michael Aug 03 '17 at 12:09
  • yes, I use the persian language and Windows Forms DataGridView. – user42037 Aug 03 '17 at 12:12
  • does Sql server set on the Persian codepage? it may be that the data can't be converted to Unicode – Michael Aug 03 '17 at 12:13
  • how can i do that? – user42037 Aug 03 '17 at 12:15
  • if you check the Sql server properties it has a codepage https://learn.microsoft.com/en-us/sql/relational-databases/collations/collation-and-unicode-support , also you can chack if database type is `nvarchar` which corresponds to Unicode data – Michael Aug 03 '17 at 12:17
  • I used nvarchar to define the type of variables in sql server as string. the point is that the DataGridView show the predefined data in persian perfectly but when I want to chage/edit the selected data it shows the ? mark – user42037 Aug 03 '17 at 12:22
  • could you try to use Sql Parameters instead of string concatenation in the query? – Michael Aug 03 '17 at 12:25
  • Possible duplicate of [How to create NVarchar(max) Sqlparameter in C#?](https://stackoverflow.com/questions/21087950/how-to-create-nvarcharmax-sqlparameter-in-c) – mjwills Aug 03 '17 at 12:28

2 Answers2

0

Change:

sqlStr = "Update Employee Set FirstName = '" + FirstName.Text + "' Where ID = '" + ID.Text + "'";

to:

sqlStr = "Update Employee Set FirstName = N'" + FirstName.Text + "' Where ID = N'" + ID.Text + "'";

Without the N at the start, you are using varchar rather than nvarchar. Which basically means that Persian characters will show as ?

mjwills
  • 23,389
  • 6
  • 40
  • 63
0

I think you should use SqlParameters like this:

sqlStr = "Update Employee Set FirstName = @FirstName Where ID = @Id";

SqlParameter param  = new SqlParameter();
param.ParameterName = "@FirstName";
param.Value         = FirstName.Text;
cmd.Parameters.Add(param);

param  = new SqlParameter();
param.ParameterName = "@Id";
param.Value         = ID.Text;
cmd.Parameters.Add(param);

This, also, avoid sql injection.

aperezfals
  • 1,341
  • 1
  • 10
  • 26