Search code examples
c#winformstextbox

How to limit the textbox input characters count?


When I get my specific data from a DataGridView and I want to put it in TextBox, I want the TextBox to just accept 11 characters, not more.

How do I achieve that?

textBox3.MaxLength = 11;
textBox3.Text= dataGridView1.CurrentRow.Cells["Phone Number"].Value.ToString();

Solution

  • Use SubString to truncate the string.

    // Set the MaxLength, may not be needed if the field cannot be altered manually
    textBox3.MaxLength = 11;
    
    // Get the text value
    var text = dataGridView1.CurrentRow.Cells["Phone Number"].Value.ToString();
    
    // Starting from the first character, take up to 11 characters max
    textBox3.Text = text.Substring(0, text.Length > 11 ? 11 : text.Length);
    

    Example:

    string longString = "abcdefghijklmnop";
    string shortString = "abcde";
    

    Result:

    longString would show abcdefghijk
    shortString would show abcde