Search code examples
c#textbox

C# TextBox that allows a maximum of one dot


How can I make a TextBox in C# to allow a maximum of one . (dot)?

Thus, abcdef and abc.def would be valid inputs whereas ab.cd.ef wouldn't.

By allow I mean that the user should not be able to enter a dot if there is already one in the text field.

Java has DocumentFilters for that purpose, is there something similar in C#?


Solution

  • I guess this is for validating user inputs. You should create a button and tell the user when he is done, press it so that you can check whether there is only one . in the string.

    Assumptions:

    Let your text box be called tb. Let your button's Click event handler be BtnOnClick.

    Now we can start to write code. First create the handler:

    private void BtnOnClick (object sender, EventArgs e) {
    
    }
    

    In the handler, you need to loop through the string and check each character. You can use a foreach for this:

    int dotCount = 0;
    string s = tb.Text;
    if (s.StartsWith(".")) //starts with .
        //code to handle invalid input
        return;
    if (s.EndsWith(".")) //ends with .
        //code to handle invalid input
        return;
    foreach (char c in s) {
        if (c == '.') {
            dotCount++;
        }
        if (dotCount >= 2) { //more than two .
            //code to handle invalid input
            return;
        }
    }
    // if input is valid, this will execute
    

    Alternatively, you can use a query expression. But I think you are unlikely to know what that is.

    string s = tb.Text;
    if (s.StartsWith(".")) //starts with .
        //code to handle invalid input
        return;
    if (s.EndsWith(".")) //ends with .
        //code to handle invalid input
        return;
    var query = from character in s
                where character == '.'
                select character;
    if (query.Count() > 1) {
        //code to handle invalid input
        return;
    }
    // if input is valid, this will execute