Marek
Marek

Reputation: 3575

SqlCommand parameter replace

I tried to Replace sign "," with "." on UPDATE parameter but I'm not able to solve it. This parameter updates numeric type from textBoxes inSQL DB.

I thought that it can me done something like this, but parameter does not contain definiton Replace. is there any way to do that?

 prikaz.Parameters.AddWithValue("@poc_kli", poc_kli.Text).Replace(',', '.');

Upvotes: 1

Views: 1508

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063338

Parse the value first; then use typed data in the parameter. For example:

decimal val = decimal.Parse(poc_kli.Text);
prikaz.Parameters.AddWithValue("poc_kli", val);

Rather than "replace", you should use an appropriate CultureInfo (if it differs from the default culture) when parsing the value. For simplicity I'm assuming that you do not in fact need to specify a culture, but that this was simply an attempt at making SQL Server happy. But for example:

CultureInfo culture = CultureInfo.InvariantCulture;
// ^^^ or GetCulture, CurrentCulture, etc
decimal val = decimal.Parse(poc_kli.Text, culture);

Even better would be to completely separate your data access code from your UI code:

decimal val = decimal.Parse(poc_kli.Text);
SomeDatabaseMethod(val, ...other args);

...

public void SomeDatabaseMethod(decimal pocKli, ... other parameters ...)
{
    ...
    prikaz.Parameters.AddWithValue("poc_kli", pocKli);
    ...
}

The fact that you have one line of code that touches both the UI and the database (which are completely unrelated, or should be) should concern you.

Upvotes: 4

Adrian Wragg
Adrian Wragg

Reputation: 7401

You're replacing at the wrong place in your code. Try:

prikaz.Parameters.AddWithValue("@poc_kli", poc_kli.Text.Replace(',', '.'));

Upvotes: 2

Related Questions