需要将文本框值更改为印度货币格式(在文本更改事件上)

时间:2016-05-23 11:39:20

标签: c# wpf cultureinfo

我写过一个只允许整数值到文本框的事件。

现在我的附加要求是我需要将Textbox Integer值更改为印度货币格式(我需要在WPF中的OnTextchanged事件中实现此目的)

   private void validateTextInteger(object sender, EventArgs e)
    {
        NumberFormatInfo nfi = new CultureInfo("en-IN", false).NumberFormat;
        nfi = (NumberFormatInfo)nfi.Clone();
        nfi.CurrencySymbol = "";
        Exception X = new Exception();
        TextBox T = (TextBox)sender;
        try
        {
            if (T.Text.Trim() != "-")
            {
                int x = int.Parse(T.Text);
                T.Text = string.Format(nfi, "{0:C0}", x);
                return;
            }
        }
        catch (Exception)
        {
            try
            {
                int CursorIndex = T.SelectionStart - 1;
                T.Text = T.Text.Remove(CursorIndex, 1);
                //Align Cursor to same index
                T.SelectionStart = CursorIndex;
                T.SelectionLength = 0;
            }
            catch (Exception)
            { 
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您好我通过使用以下代码实现了它

    private void validateTextInteger(object sender, EventArgs e)
    {


        NumberFormatInfo nfi = new CultureInfo("en-IN", false).NumberFormat;
        nfi = (NumberFormatInfo)nfi.Clone();
        nfi.CurrencySymbol = "";
        Exception X = new Exception();
        TextBox T = (TextBox)sender;
        try
        {
            if (T.Text.Trim() != "-")
            {
                var val = T.Text.Trim();
                int x=0;
                val = val.Replace(",", "");
                if (!(val.Contains(',')))
                {
                     x = int.Parse(val);
                }
                string  s  = string.Format(nfi, "{0:C0}", x);
                T.Text = s.Trim();
                T.SelectionStart = T.Text.Length ;
                T.SelectionLength = 0;
                return;
            }
        }
        catch (Exception)
        {
            try
            {
                int CursorIndex = T.SelectionStart - 1;
                T.Text = T.Text.Remove(CursorIndex, 1);
                //Align Cursor to same index
                T.SelectionStart = T.Text.Length;
                T.SelectionLength = 0;
            }
            catch (Exception)
            { 
            }
        }
    }