0

In a C# windows forms class I am binding my textboxes like this.

this.textMargin.DataBindings.Add(new Binding("Text", dt, "Margin", true, DataSourceUpdateMode.OnValidation, 0, "P"));

This is fine for displaying the textbox "textMargin" as a percent. But, when I pass the value of the text box to my update statement, I get a string format error even though I am trying to use Decimal.Parse like this:

decimal testconvert = Decimal.Parse(this.textMargin.Text);

The value I am trying to pass is '100%', but it needs to submit back to the database as 1.

What is the secret here?

Thanks

4

4 に答える 4

4

試す

string textMargin = this.textMargin.Text.EndsWith("%") ? this.textMargin.Text.Replace("%","") : this.textMargin.Text;

decimal testconvert = Decimal.Parse(textMargin) / 100;
于 2012-10-06T21:16:31.017 に答える
1

%は 10 進数の有効な部分ではないため、 で解析できませんDecimal.Parse

解析する前に、文字列からそれをクリアする必要があります。

于 2012-10-06T19:48:47.197 に答える
0

ご覧のとおりDecimal.Parse、数字以外の値は受け入れませんが、以下のような単純なアルゴリズムを使用して数字以外を取り除くことができます。

    public static string RemoveNonDigits(string s)
    {
        string newS = "";
        if (s.Length == 0) return newS;
        for (int i = 0; i < s.Length; i++)
        {

            if (Char.IsDigit(s[i]) || s[i] == '.')
                 newS += s[i];

            else if (!Char.IsDigit(s[i]))
            {
                newS += "";
            }

            return newS;
        }

その後、あなたは呼び出すことができます

Decimal percent = Decimal.Parse(RemoveNonDigits(textMargin.Text.ToString()));
于 2012-10-06T19:48:37.753 に答える