Reputation: 109
i have a form with 6 textboxes and a delete button.that i want to do is to read a text file and save it into a list.after that i want to give a value at the textbox1 and delete the row from the list that this value exists.with this code(i have already done) delete all the values from the text file.what should i change to the code?i use Microsoft Visual C# 2010 Express.
List<string> StoreItems;
public Form1()
{
InitializeComponent();
filePath = @"C:\Users\v\Desktop\text.txt";
StoreItems = new List<string>();
}
private void button3_Click(object sender, EventArgs e)
{
using (var streamReader = new StreamReader(filePath, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
StoreItems.Add(streamReader.ReadLine());
}
}
using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
foreach (string line in StoreItems)
{
if(line == textBox1.Text)//remove all from the list
StoreItems.Remove(line);
}
}
}
Upvotes: 1
Views: 5976
Reputation: 612993
You can use RemoveAll()
.
Removes all the elements that match the conditions defined by the specified predicate.
There's no need for explicit iteration over the list. You can just call it like this:
StoreItems.RemoveAll(item => item == textBox1.Text);
You also forgot to write the list back to the file. I think you want code like this:
using (var streamReader = new StreamReader(filePath, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
StoreItems.Add(streamReader.ReadLine());
}
}
StoreItems.RemoveAll(item => item == textBox1.Text);
using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
foreach (string line in StoreItems)
{
streamWrite.WriteLine(line);
}
}
Upvotes: 2
Reputation: 6882
using (var streamReader = new StreamReader(filePath, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
StoreItems.Add(streamReader.ReadLine());
}
}
int i = StoreItems.IndexOf(textBox1.Text);
while (i >= 0)
{
StoreItems.RemoveAt(i);
i = StoreItems.IndexOf(textBox1.Text);
}
Upvotes: 2