open and save file dialog - c#

i use an openFileDialog to read from a text file and print the values in a listbox and a saveFileDialog to save the changes in textfile.i wrote this code but it doesn't work.if a change the listbox with a textbox works fine.But i need to print and save the items into a listbox.any suggestions?
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label7.Text = openFileDialog1.FileName;
listBox1.Text = File.ReadAllText(label7.Text);
}
}
private void button5_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Text);
}
}

You need to add each line of the file as a listbox item. Then, to save, loop through each listbox item and write it as a new line.
You can use File.ReadAllLines and listBox1.Items.AddRange to add the items.
listBox1.Items.AddRange(File.ReadAllLines(openFileDialog1.FileName));
Since the Items property contains objects, not strings, you will need to manually loop over the items and write them individually... perhaps doing something like
StringBuilder sb = new StringBuilder();
foreach(object item in listBox1.Items) {
sb.AppendLine(item.ToString();
}
File.WriteAllText(saveFileDialog1.FileName, sb.ToString());

ListBox.Text represents only a selected part of the list box items.
A quote from MSDN docs:
When the value of this property is set to a string value, the ListBox searches for the item within the ListBox that matches the specified text and selects the item. You can also use this property to determine which items are currently selected in the ListBox
This should work :
using System.Linq;
...
string[] lines = File.ReadAllLines(fileName);
listBox.Items.AddRange(lines.ToArray<object>());

Related

Dont Save Item in ComboBox

I have a TextBox, a Button, and a Combobox
When I click the Button, I want the text in Textbox to be added to the Combobox Items
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(textBox1.Text);
}
My form until open. This text shows in the Combobox, but when I close the Form and open it again the text is not longer shown in the Combobox.
I want to save the text to the Collection Items of the Combobox. I don't want to use a database.
As others have mentioned in the comments, you need to understand and decide where you wish to store your values.
For the purpose of my example, I have created a simple text file to store these values. The code reads from the file and adds each line as an item into the ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
// Read items from file into a string array
string[] items = System.IO.File.ReadAllLines(#"D:\ComboBoxValues.txt");
// Add items to the comobobox when opening the form
comboBox1.Items.AddRange(items);
}
private void button1_Click(object sender, EventArgs e)
{
// Add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
// Put all existing comobo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
// Save the array of items to a text file (this will not append, it will re-write the file)
System.IO.File.WriteAllLines(#"D:\ComboBoxValues.txt", items);
}
This may not be the most elegant way of going about it, but from the point of providing you an understanding - this should be more than sufficient.
if you don't like to use File System, you can use Preferences(but it's not recommendable to use preference to memorize large values), check this link to see how create a new setting
private void Form1_Load(object sender, EventArgs e)
{
string[] strItems = Properties.Settings.Default.items.Split(", ");
for(int i = 0; i < strItems.length; i++) {
comboBox1.Items.Add(strItems[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
//put all existing combo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
for(int i = 0; i < items.length; i++) {
//I assumed you had an items key in your settings
if(i == items.length - 1) {
Properties.Settings.Default.items += value;
} else {
Properties.Settings.Default.items += value + ", ";
}
}
//then you should to save your settings
Properties.Settings.Default.Save();
}

How to allow the user to copy items from listbox and paste outside of windows form

I know that, for data grids, users can select the items, copy them, and then paste them outside of the form. Is there was a way to do that with listboxes? It looks like you can select multiple items in the listbox but it doesn't appear that it actually copies it if you try to paste the selected values outside of the form.
You can catch the event when user click ctrl + c to put the item to the clipboard.
This code is for the list box with multi-selection MultiSimple=true
private void ListBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
System.Text.StringBuilder copy_buffer = new System.Text.StringBuilder();
foreach (object item in ListBox1.SelectedItems)
copy_buffer.AppendLine(item.ToString());
if (copy_buffer.Length > 0)
Clipboard.SetText(copy_buffer.ToString());
}
}
To copy selected item via Ctrl+C use this code:
private void LstVehicles_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.C))
{
Clipboard.SetText(this.yourListBoxName.SelectedItem.ToString());
}
}
Those 2 solutions didn't work for me, what did work was though clicking on the listBox, and generating a function called
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
inside I put...
Clipboard.SetDataObject(this.listBox1.SelectedItem.ToString());
So the complete solution was
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Clipboard.SetDataObject(this.listBox1.SelectedItem.ToString());
}
So did get a line from one of the solutions and one of the comments.
Thanks.
I can select only one line in the listbox, I know it not the best,
but by code below left mouse click copy all the listbox Items
to the Clipboard:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Text.StringBuilder copy_buffer = new System.Text.StringBuilder();
foreach (object item in listBox1.Items)
copy_buffer.AppendLine(item.ToString());
if (copy_buffer.Length > 0)
Clipboard.SetText(copy_buffer.ToString());
}

Reading from text file and populate to Listbox with Button

I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.
How do I do it so that it reads the file and only include new input data?
private void Button_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Listbox1.Items.Add(line);
}
sr.Close();
}
}
The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox:
private void Button_Click(object sender, RoutedEventArgs e)
{
Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
}
As Clemens said in comment, you can either Listbox1.Items.Clear() or Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
But this would always replace all your listbox with the file. If you just want, as you said, to enter new data, you could simply check if if(!Listbox1.Items.Contains(line)) before adding the item.
Depends on what you really want, reupdate the whole list or just add new entries and not removing old ones.

How to copy selected item in list box in C#?

How to copy selected item in list box to clipboard, using right click "Copy" menu?
If you want to select an item, and do ctrl + c then use this code:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.C)
{
string s = listBox1.SelectedItem.ToString();
Clipboard.SetData(DataFormats.StringFormat, s);
}
}
To copy all the items in the listbox to the clipboard:
Clipboard.SetText( string.Join( Environment.NewLine, ListBox1.Items.OfType<string>() ) );
To copy just the selected lines in the listBox to the clipboard (listbox SelectionMode is MultiExtended):
Clipboard.SetText( string.Join( Environment.NewLine, ListBox1.SelectedItems.OfType<string>() ) );
To manipulate text in the clipboard, you can use the static Clipboard class:
Clipboard.SetText("some text");
http://msdn.microsoft.com/en-us/library/system.windows.clipboard(v=vs.110).aspx
I clicked on my listbox to create an automatic function inside the form class.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Clipboard.SetDataObject(this.listBox1.SelectedItem.ToString());
}
I added the Clipboard.SetDataObject() line and it works.

c# listbox - first selected item is played

Here is my problem: I have a TextBox, button, and a ListBox. The functions works right but whenever I search flash videos, the moment I click the search button, the first video on the list is played. I don't want it to be played on that time - I want to choose from the list without playing the first highlighted item on the ListBox.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
var path = "C:\\Users\\John\\Desktop\\Video\\FLASH";
listBox1.DataSource = Directory.GetFiles(path, "*" + txtbox1.Text + "*")
.Select(f => Path.GetFileName(f))
.ToList();
}
This is the search button. It will search the text on textbox1 from the specified path:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var fileName = listBox1.SelectedItem as string;
if (fileName != null)
{
var path = Path.Combine("C:\\Users\\John\\Desktop\\Video\\FLASH", fileName);
Process.Start(path);
}
}
This is the ListBox, the searched items will be here, but there is always one item selected and that item plays whenever the search finished.
Fill the list, then add the selectedindexchanged event handler. (Make sure that the event isn't added for you by the designer).
So,
listBox1.DataSource = ...
listBox1.SelectedIndexChanged +=
new System.EventHandler(this.listBox1_SelectedIndexChanged);

Categories