Question

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);
    }
Was it helpful?

Solution 2

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;
}

OTHER TIPS

You want this to be handled by your Button's Click event and not the TextBox's TextChanged event.

Like this:

private void saveButton_Click(object sender, RoutedEventArgs e)
{
       using (var streamWriter = new StreamWriter("yourtextfile.txt", true))
       {
             streamWriter.WriteLine(textBox.Text);
       }
}

You don't need the TextChanged event at all.

xaml

<TextBox Name="textToSave" />
<Button Click="saveToTextFile" />

cs

private void saveToTextFile(...){
   string text = textToSave.Text;

   //code to save to text file

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top