Dark Knight
Dark Knight

Reputation: 3577

Restricting number of continuous comma in a textbox

how to limit the number of continuous 'comma' in a textbox?...ex it should not allow user to enter more than 2 comma continuously

Upvotes: 1

Views: 672

Answers (2)

Javed Akram
Javed Akram

Reputation: 15344

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyChar == ',')
    {
       if(TextBox.Text.Contains(",,"))
       {
           e.Handled = true;
       }
    }
}

Upvotes: 1

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

This should handle most scenarios, I believe:

private void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        int pos = tb.SelectionStart;
        int length = tb.Text.Length;
        tb.Text = tb.Text.Replace(",,", ",");
        int diff = length- tb.Text.Length;
        tb.SelectionStart = pos == 0 || diff == 0 ? pos : pos - diff;
    }
}

This works when you type text into the TextBox, as well as when you paste text into it.

Upvotes: 4

Related Questions