Search code examples
c#wpfnulltextbox

The textbox should never be empty. c#


I don't want my Textbox to be empty. I want it to keep the value before it is empty and write it when it is deleted. I'm using the KeyDown event but it doesn't work. Not triggering when the Delete key is pressed. Which event would be appropriate to trigger this correctly.

My Code

private static void textBox_KeyDown(object sender,KeyEventArgs e)
    {
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);
        var oldValue = textBox.Text;
        if (e.Key == Key.Delete)
        {
            if (textBox.Text == string.Empty || textBox.Text == "")
            {
                MessageBox.Show("Not null");
                textBox.Text = oldValue;
            }
        }
    }

Solution

  • You could handle TextChanged and store the previous value in a field:

    private string oldValue = string.Empty;
    
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (string.IsNullOrEmpty(textBox.Text))
        {
            MessageBox.Show("Not null");
            textBox.Text = oldValue;
        }
        else
        {
            oldValue = textBox.Text;
        }
    }
    

    Note that oldValue will be reset on each keypress. Also note that string.Empty is equal to "" so you don't need two conditions to check whether the string is empty.