-
Combobox writer
Hi there,
I'm trying to do something quite simple, but I just cant figure it out.
I am trying to write all of the content in a combobox to a text file, the problem is, it just wont work as I want it it.
Here is my current code:
Code:
using (FileStream stream = new FileStream("include/bank.txt", FileMode.Create))
using (TextWriter writer = new StreamWriter(stream))
{
for (int x = 0; x <= cbBanken.Items.Count; x++ )
{
cbBanken.SelectedItem = x;
writer.WriteLine(cbBanken.SelectedItem.ToString());
}
}
At the moment it's always writing the first line in the combobox, and nothing else. I cant seem to find out what's wrong. I've tried a foreach loop too, but that didn't go too wel either.
Any help would be very much apreciate!
-
Re: Combobox writer
You are telling it to write the currently selected item each time
Code:
writer.WriteLine(cbBanken.SelectedItem.ToString());
You want it to print the item at the index specified by x
Code:
writer.WriteLine(cbBanken.Items[x].ToString());
-
Re: Combobox writer
Code:
for (int x = 0; x <= cbBanken.Items.Count; x++)
{
writer.WriteLine(cbBanken.Items[x].ToString());
}
That is the code I'm currently using. Thank you for the help.
However, it's now giving me an error when I click the button:
InvalidArgument=Value of 1 is not appropriate for index. Parametername: index
-
Re: Combobox writer
have the loop continue while x is less than Items.Count, not less than or equal to
Code:
for (int x = 0; x < cbBanken.Items.Count; x++)
-
Re: Combobox writer
Or better yet, use a foreach loop.
-
Re: Combobox writer
Is there a cbBanken.Items.ToString() member? If there is it may do what you want, sorry I can't check presently....
If it does what you want then there may be a one liner....
Code:
File.WriteAllText(@"include/bank.txt", cbBanken.Items.ToString());
-
Re: Combobox writer
Alright, thank you for the help. I'm sure I'll be able to pull it off now. :)
I'm now stuck on a stream I didn't close, probably. It's telling me the file is in use while I've checked every line to make sure I closed everything properly.
Aah well, I'm sure I'll find out. Thank you all for your time. :)
-
Re: Combobox writer
You are using a 'using' statement in your example code, so that file is definitely being closed when the scope of the using statement ends.
-
Re: Combobox writer
Code:
FileStream stream = new FileStream(lFileName.Text.ToString() + ".txt", FileMode.Create); //bank.txt
using (TextWriter writer = new StreamWriter(stream))
{
File.WriteAllText(stream.ToString(), cbBanken.Items.ToString());
}
Alright, this manages to delete the file because it's using filemode.create
Howéver, it will not write to the file. Instead it will make a data file called "System.IO.FileStream". I'm guessing 'stream.ToString()' is wrong, so.. any suggestions? :)
Edit:
I tried swapping 'stream.ToString()' with 'lFileName.Text.ToString() + ".txt"', but then I got a message saying it doesn't support the file path.