C# Save all items in a ListBox to text file - c#

Recently I've been quite enjoying C# and I'm just testing with it but there seems to be one part I don't get.
Basically I want it so that when I click the SAVE button must save all the items in the listbox to a text file. At the moment all it comes up with in the file is System.Windows.Forms.ListBox+ObjectCollection.
Here's what I've got so far. With the SaveFile.WriteLine(listBox1.Items); part I've tried putting many different methods in and I can't seem to figure it out. Also take in mind that in the end product of my program I would like it to read back to that to that text file and output what's in the text file to the listbox, if this isn't possible then my bad, I am new to C# after all ;)
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
SaveFile.WriteLine(listBox1.Items);
SaveFile.ToString();
SaveFile.Close();
MessageBox.Show("Programs saved!");
}

From your code
SaveFile.WriteLine(listBox1.Items);
your program actually does this:
SaveFile.WriteLine(listBox1.Items.ToString());
The .ToString() method of the Items collection returns the type name of the collection (System.Windows.Forms.ListBox+ObjectCollection) as this is the default .ToString() behavior if the method is not overridden.
In order to save the data in a meaningful way, you need to loop trough each item and write it the way you need. Here is an example code, I am assuming your items have the appropriate .ToString() implementation:
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach(var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}

Items is a collection, you should iterate through all your items to save them
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
MessageBox.Show("Programs saved!");
}

There is one line solution to the problem.
System.IO.File.WriteAllLines(path, Listbox.Items.Cast<string>().ToArray());
put your file path+name and Listbox name in above code.
Example:
in Example below path and name of the file is D:\sku3.txt and list box name is lb
System.IO.File.WriteAllLines(#"D:\sku3.txt", lb.Items.Cast<string>().ToArray());

Related

ListBox Controls in Winform

I would like to perform 2 different actions. I have a Form where CSV File Containing two Column(Data and Image) will be read and and displayed from a path. I've used the CSVReader but I'm not sure how to implement the picturebox and listbox display portion.
For the listbox, I created a list(record). all the properties are in this List, But when I go to display it, it shows just the name of the Class as a list for all of them. I would like the name to be the Value of Data(For Example with the image referenced it would be StackIndex=1of10
Here is my Code for Displaying the List:
public Viewer()
{
InitializeComponent();
_path = #"\\ikscp0207\Images\Debug\Debug.csv";
List<Elements> records; //each row of csv will represent one object in the elements class thats generated. Here we need a list
using (var reader = new StreamReader(_path)) //Standard Stream reader for File Reading Setup. ReadFile is Hard Coded in this Iteration.
using(var csv = new CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture)) //Takes the reader and generates new csv reader,
//which is used by csvhelper to get all the records
//in list of elements and converting it into a list.
{
records = csv.GetRecords<Elements>().ToList();
}
ListControl.DataSource = records;
}
Here is what the listbox looks like
the next thing is that I would like to be able to navigate up and down the listbox and display the appropriate image column data in a textbox. This is a sample of the CSV File I have put in a button but have not been successful in doing so.
private void PushNext_Click(object sender, EventArgs e)
{
int next = Convert.ToInt32(ListControl.SelectedIndex) + 1;
this.ListControl.Focus();
this.ListControl.Items[next] = true;
I'm able to increment it, but I'm getting an exception where it shows "Items collection cannot be modified when the DataSource property is set.

Read Multiple Textfile upon Button Click and Display Content

I initially have a Fileupload tool to upload a textfile, manipulate its content and display into a Listbox or Textbox. The limitation however is Fileupload only supports single uploading, at least to the version of .Net Framework I am using.
What I intend to do is just use a button control and remove the Fileupload. Upon Button click I need to read the textfiles inside a designated folder path and display first the contents inside a multiple lined textbox. (not just the file name) This is my intially written codes, and it is not working.
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}
Since your's is web based application you can't access physical paths like c:\\.. you should use Server.MapPath anyway(As per the comment, you don't need to get the file with Server.MapPath). Then for getting the content you can try something like the following:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(#"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(#"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}
you wrote content += content;, that is the problem. change it to content += file.Name;, it will work.

Select one string line in a list

I'm trying to simply select one string line out a long list strings that are held on a server and seperated with a pipe character. This string is grabbed by a php script and the string line is a list of all the media and folders I have on my server.
In my code I'm getting this information and returning it with the following code:
using (var client = new WebClient())
{
result = client.DownloadString("http://server.foo.com/images/getDirectoryList.php");
}
textBox1.Text = string.Join(Environment.NewLine, result.Split('|'));
And it looks like this:
But when I try to simply click on one of them, my cursor simply just goes to where I've clicked. Like this, I tried to select md-harrier.jpg and my cursor just ends up at the end of jpg:
What I'm really wanting is pictured below. I click on Koala.jpg and the whole thing is highlighted and I have the ability to store the name of what it is I've just clicked on. TO achieve that screen shot I had to click next to Koala.jpg and then drag my mouse along.
Is there anyway I can achieve what I want to achieve?
The key thing to note about this is that I will have no idea how many files will be on the server, nor what they will be called. My php script is grabbing this information and displaying it in my winform text box using the code I have wrote above.
as Simon said you need a ListBox, a ListBox fits here because it allows you to select a line, and you can register to the event of SelectedIndexChanged and store the name that was selected.
to initiate the values do
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
listBox1.Items.AddRange(result.Split('|'));
listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
and on the selectedItemChanged:
string currVal;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currVal = (string)listBox1.SelectedItem;
}
As you said you have no reason to use TextBox,then by using ListBox you can achieve that in this way;
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
string[] names=result.Split('|');
foreach(string name in names)
{
if(name!="|"&&name!=" ")
{
listbox.Items.Add(name);
}
}
Additionally,if you would like to store selected item in a variable subscribe to ListBox's SelectionChangedEvent and store the selection index in a variable in this way;
int selection=;
private void ListBox1_SelectionIndexChanged(object sender,EventArgs e)
{
selection=ListBox1.SelectedIndex;
}

Saving from a list box to a .csv file in c# Win Form

I have been looking around for hours on how to do this, I think the best idea is to come up with a for each loop and then pass that through into the Stream Writer.
I've tried multiple different ways, and I think maybe I'm just not good enough to see my error, if anyone would be able to help that's be great.
Currently the file gets created and the only output I get for it is "System.Windows.Forms.ListBox+ObjectCollection" on the first line, which suggests to me that I'm not passing the values out properly.
Here's the code :
private void btnSave_Click(object sender, EventArgs e)
{
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
myOutputStream.WriteLine(lstBox.Items);
myOutputStream.Close();
//foreach (object item in lstBox.Items)
//string listString = lstBox.SelectedItem.ToString();
//StreamWriter streamBox = File.CreateText(#"testfile.csv");
//streamBox.Write(listString);
//streamBox.Close();
//if (SaveFileDialog.ShowDialog() == DialogResult.OK)
//{
// System.IO.StreamWriter streamBox = new System.IO.StreamWriter(SaveFileDialog);
// foreach (object item in lstBox.Items)
// streamBox.WriteLine(item.ToString());
// streamBox.Close();
//}
}
All the commented out parts are things I've tried in the past. But right now, I think the simplest way was the top three lines.
Thanks for your input.
You are writing out listBox.Items, which is an ListBoxObjectCollection. You need a foreach loop to write each item:
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
myOutputStream.Close();
Also note that you can use a using block here:
using (StreamWriter myOutputStream = new StreamWriter("Myfile.csv"))
{
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
}
First, what's in the ListBox? If the items in the list box are just string items, then you could do the following:
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (string item in lstBox.Items) {
myOutputStream.WriteLine(item);
}
myOutputStream.Close();

Dynamically adding LinkLabels to a TableLayoutPanel

I've been having a problem with the following code:
namespace Viewer
{
public partial class Form1 : Form
{
int count = 0;
LinkLabel[] linkLabel = new LinkLabel[200];
string filename;
string extension;
string filepath;
private void btnLoad_Click(object sender, EventArgs e)
{
// Creates a Directory for the Movies Folder
DirectoryInfo myDirectory = new DirectoryInfo(#"C:\Users\User\Movies");
// Creates a list of "File info" objects
List<FileInfo> ls = new List<FileInfo>();
// Adds filetypes to the list
ls.AddRange(myDirectory.GetFiles("*.mp4"));
ls.AddRange(myDirectory.GetFiles("*.avi"));
// Orders the list by Name
List<FileInfo> orderedList = ls.OrderBy(x => x.Name).ToList();
// Loop through file list to act on each item
foreach (FileInfo filFile in orderedList)
{
// Creates a new link label
linkLabel[count] = new LinkLabel();
// Alters name info for display and file calling
filepath = filFile.FullName;
extension = filFile.Extension;
filename = filFile.Name.Remove(filFile.Name.Length - extension.Length);
// Write to the textbox for functional display
textBox1.AppendText(filename + "\r\n");
// Alters link label settings
linkLabel[count].Text = filename;
linkLabel[count].Links.Add(0, linkLabel[count].Text.ToString().Length, filepath);
linkLabel[count].LinkClicked += new LinkLabelLinkClickedEventHandler(LinkedLabelClicked);
// Adds link label to table display
tblDisplay.Controls.Add(linkLabel[count]);
// Indexes count up for arrays
count = count + 1;
}
}
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(filepath);
}
}
}
My goal is to generate a table of links to all of the media files that I add at launch, and have the links open the files in their respective players.
As of right now, it generates all of the links properly, but whenever I click on any of them, it launches the last item in the list.
For example, if the list contains "300", "Gladiator", and "Top Gun", no matter which link I click, it opens "Top Gun".
I assume that this has to do with it calling the variable "filepath" in the click event, which is left in it's final state. However, I'm not exactly clear on how to create a static link value or action on each individual link, as all of the answers I've researched are in regards to single linklabel situations, not dynamic set-ups.
Any help/advice would be appreciated!
Try as below:
In foreach loop add one line more like:
linkLabel[count].Tag = filepath;
then in click event get this path as blow,
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filepath = ((LinkLabel)sender).Tag.tostring();
System.Diagnostics.Process.Start(filepath);
}

Categories

Resources