Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to write some code to format the numeric inputs in a TextBox that each three digit is seperated with a comma, like this: 1,648,195 But I want to format the input in textbox when typing.I work like it in vb.net by selection start property but in c# I do not work please help me
Posted
Comments
rezaeti 6-Oct-15 17:20pm    
Is there any one to help?

$('input.number').keyup(function(event) {

// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;

// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
 
Share this answer
 
v2
Here's a sketch on what approach I would choose. You still need to play around with CaretIndex.

C#
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace WpfApplication1
{
    public class TextBoxCustomNumber : TextBox
    {
        private const string _GROUP_NAME_IS_NEGATIVE = "isNegative";
        private const string _GROUP_NAME_INTEGER = "integer";
        private const string _GROUP_NAME_DOT = "dot";
        private const string _GROUP_NAME_FRACTION = "fraction";
        private static readonly Regex _RegexNumber = new Regex(@"\A(?<" + _GROUP_NAME_IS_NEGATIVE + @">-)?(?<" + _GROUP_NAME_INTEGER + @">[0-9]+)*(?<" + _GROUP_NAME_DOT + @">\.)?(?<" + _GROUP_NAME_FRACTION + @">[0-9]*)\z");
        private string _oldText;

        public TextBoxCustomNumber()
        {
            TextChanged += OnTextChanged;
        }

        private void ApplyResults(string numberFormattedStr, int caretIndex)
        {
            if (!Text.Equals(numberFormattedStr))
            {
                Text = numberFormattedStr;
                CaretIndex = caretIndex;
                _oldText = numberFormattedStr;
            }
        }

        private void OnTextChanged(object sender, TextChangedEventArgs textChangedEventArgs)
        {
            var text = Text;

            // empty field
            if (string.IsNullOrEmpty(text))
            {
                ApplyResults("", 0);
                return;
            }

            // allow only numbers
            var match = _RegexNumber.Match(text.Replace(",", ""));
            if (!match.Success)
            {
                // not a number => restore old value
                ApplyResults(_oldText, CaretIndex);
                return;
            }

            // number => try to format
            var numberAndFormattedStr = ConstructAndFormat(
                    match.Groups[_GROUP_NAME_IS_NEGATIVE].Success,
                    match.Groups[_GROUP_NAME_INTEGER].Success ? match.Groups[_GROUP_NAME_INTEGER].Value : "",
                    match.Groups[_GROUP_NAME_DOT].Success,
                    match.Groups[_GROUP_NAME_FRACTION].Success ? match.Groups[_GROUP_NAME_FRACTION].Value : ""
                    );
            var number = numberAndFormattedStr.Item1;
            var numberFormattedStr = numberAndFormattedStr.Item2;

            // calculate caret index
            // ...

            ApplyResults(numberFormattedStr, CaretIndex);
        }

        private static Tuple<decimal?, string> ConstructAndFormat(bool isNegative, string integerStr, bool dot, string fractionStr)
        {
            var numberStr = (isNegative ? "-" : "") + integerStr + (dot ? "." : "") + fractionStr;

            decimal numberAbs;
            if (!decimal.TryParse(numberStr, out numberAbs))
            {
                return new Tuple<decimal?, string>(null, numberStr);
            }
            numberAbs = Math.Abs(numberAbs);

            var sbFractionFormatter = new StringBuilder();
            for (var i = 0; i < fractionStr.Length; i++)
            {
                sbFractionFormatter.Append('0');
            }

            var numberFormattedStr = string.Format("{0}{1:#,##0." + sbFractionFormatter.ToString() + "}{2}",
                isNegative ? "-" : "",
                numberAbs,
                string.IsNullOrEmpty(fractionStr) && dot ? "." : ""
                );

            return new Tuple<decimal?, string>(numberAbs, numberFormattedStr);
        }
    }
}
 
Share this answer
 
v2
another solution I just found:

C#
TextChanged += (sender, args) =>
{
    try
    {
        int iKeep = SelectionStart - 1;
        for (int i = iKeep; i > 0; i--)
            if (Text[i] == ',')
                iKeep -= 1;

        Text = String.Format("{0:N0}", Convert.ToInt32(Text.Replace(",", "")));
        for (int i = 0; i < iKeep; i++)
            if (Text[i] == ',')
                iKeep += 1;

        SelectionStart = iKeep + 1;
    }
    catch
    {
        //errorhandling
    }
};
 
Share this answer
 
Refer - Masked Input Plugin[^].

You just need to attach this plugin to your app and play.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900