Search code examples
c#wpftextchanged

WPF TextChanged event


I have a TextBox and a Button inside my WPF application. When the user clicks on the button it saves the textbox's text value into a txt file. So, basically when the user inserts something in the TextBox, the TextChaned event is triggered. The problem is, for example, if the user types "Daniel" and clicks on the button, every single combination of user's input is also saved. How can I get rid of this?

The text file contains:

D
Da
Dan
Dani
Danie
Daniel

How can I save only the last string (Daniel) or is there any other event handler for my problem? Btw, this is actually a list, and I'm using the Add method.

Code, as requested:

    // Button, just ignore all the crap inside
    private void saveChangesButton_Click(object sender, RoutedEventArgs e)
    {
        System.IO.File.WriteAllLines(@System.IO.File.ReadAllText(@System.IO.Directory.GetCurrentDirectory() + "/dir.txt") + "/commandline.txt", checkedValues);
    }
    // List 
    private List<String> checkedValues = new List<String>();
    // TextChanged
    private void sWidth_TextChanged(object sender, TextChangedEventArgs e)
    {
        checkedValues.Add(sWidth.Text);
    }

Solution

  • I would try something like that:

    // List 
    private List<String> checkedValues = new List<String>();
    
    public int nTextboxChanged = 0;
    
    // Button, just ignore all the crap inside
    private void saveChangesButton_Click(object sender, RoutedEventArgs e)
    {
        if(nTextboxChanged == 1)
        {     
            checkedValues.Add(sWidth.Text);
            System.IO.File.WriteAllLines(@System.IO.File.ReadAllText(@System.IO.Directory.GetCurrentDirectory() + "/dir.txt") + "/commandline.txt", checkedValues);
        }
    }
    
    // TextChanged
    private void sWidth_TextChanged(object sender, TextChangedEventArgs e)
    {
        nTextboxChanged = 1;
    }