saving and returing listbox content C# - c#

I have a question about saving content from a listbox and putting it in a .ini file. Also i want to retrieve the information and put it back in the listbox when the programm starts.
I have two listboxes lets call them listBox1 and listBox2.
And 1 button lets call that selectbttn.
The content from listBox2 must be saved when i click on the select button. ,br />
How can i fix this?
This is the code with the 2 listboxes, id ont have a code for the select button.
The button that you see in the code is a add button that adds content from listbox1 to listbox 2.
private void add_button_Click(object sender, EventArgs e)
{
try
{
if (list_selected.Items.Contains(List_selection.SelectedItem))
{
MessageBox.Show("Can not add the type twice.");
}
else
{
list_selected.Items.Add(List_selection.SelectedItem);
}
}
catch
{
{
MessageBox.Show("No type selected");
}
}
}

You need to use a StreamWriter to save to the file. You could do something like the following:
public void SaveFile_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\YourFile.ini"))
{
foreach (var item in list_selected.Items)
{
file.WriteLine(item.ToString());
}
}
}
http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx
You can use a StreamReader to read back the contents of the .ini file when your application loads. I will leave this to you since you did not originally provide code.

Write
File.WriteAllLines("test.ini",
listbox.Items.Cast<ListItem>().Select(i => i.Text).ToArray());
Load
listbox.Items.AddRange(File.ReadAllLines("test.ini")
.Select(l => new ListItem(l)).ToArray());

Related

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.

Hide/modify string in listView

I am making a program in which users can modify remote files. I put the selected files (depending on some predefined criteria) in a listView, but I display only the file names, not full filepaths.
The problem I get however, is that when a user would double-click on an item, it should open another window to modify that item.
private void listView1_DoubleClick(object sender, EventArgs e)
{
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Text+".txt");
Form3 passForm = new Form3();
passForm.ShowDialog();
}
private void Form2_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles("\\\\myremotserver\\ftp\\","*.txt", System.IO.SearchOption.AllDirectories);
foreach (string s in files)
{
listView1.Items.Add(Path.GetFileNameWithoutExtension(s));
}
}
The problem is, that the files are all in different subfolders, so if I leave the code as is, it will not display the correct content of the file. For example, the file is called test1.txt, it is placed in myremoteserver\ftp\testfolder\test1.txt, but with my program, it will try to find the file in myremoteserver\ftp\test1.txt.
What I am asking is, if it is possible to modify the listView in such a way, that the full file path is always saved, but only the file names are displayed? I do not want the user to see the complete file path of the files, just the file names.
Use the Tag property of the ListViewItem
So to create items...
foreach (string s in files)
{
ListViewItem lvi = new ListViewItem(Path.GetFileNameWithoutExtension(s));
lvi.Tag = s;
listView1.Items.Add(lvi);
}
Then in event handler...
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Tag +".txt);

check dropdown menu if matches

Long story short: There are specific tags given (like Pop, Rock, Metal) and the User should write into a textbox and every time he adds a char the given tags are checked if one (or more) matches. At the moment I'm using a combobox with the following code:
private void EnterComboBox_TextChanged(object sender, EventArgs e)
{
List<string> AllTags = new List<string>();
AllTags.Add("Pop");
if (AlleTags[0].ToLower().StartsWith(EnterComboBox.Text.ToLower()))
{
EnterComboBox.Items.Clear();
EnterComboBox.Items.Add("Pop");
EnterComboBox.DroppedDown = true;
}
}
this is working fine but the problem is, that after the first char entered the dropbox drops down and the entered text is marked and will be overwritten when a new char is entered. Any ideas how I could fix this? Every idea is welcome it doesn't have to be a combo box :)!
Edit:
After some more (detailed) research I realized I could explain it like this: Basically I want the combobox the behave like the search-bar from google. The users enters letters and in the dropdown menu are autocomplete suggestions
At the moment I solved it like this:
I placed a textbox in front of a combobox so that only the arrow of the combobx is visible and if you click on it you automatically write in the textbox.
public Form1()
{
InitializeComponent();
EingabeTextBox.AutoSize = false;
EingabeTextBox.Size = new Size(243, 21); //the size of the combobox is 260;21
}
private void EingabeTextBox_TextChanged(object sender, EventArgs e)
{
EingabeComboBox.Items.Clear();
List<string> AlleTags = new List<string>();
AlleTags.Add("Example");
if (AlleTags[0].ToLower().StartsWith(EingabeTextBox.Text.ToLower()))
{
EingabeComboBox.Items.Add(AlleTags[0]);
EingabeComboBox.DroppedDown = true;
}
}
For me it would work like this. I hope I can help someone else with this too, but I am still open for any better ideas :)!
Changing the ComboBox entries while typing into it obviously creates undesired interferences. Instead combine a TextBox and a ListBox.
private bool changing;
private void TextBox_TextChanged(object sender, EventArgs e)
{
if (!changing) {
changing = true;
try {
// manipulate entries in the ListBox
} finally {
changing = false;
}
}
}
private void ListBox_IndexChanged(object sender, EventArgs e)
{
if (!changing) {
changing = true;
try {
// Put selected entry into TextBox
} finally {
changing = false;
}
}
}
The changing guard makes sure that the ListBox does not influence the TextBox while you are entering text into the TextBox and vice versa.
The try-finally ensures that the guard will be reset in any circumstances, even if an exception should occur.

Add textbox text to new string in list each time button is pressed

This is the code:
private void button1_Click(object sender, EventArgs e)
{
List<string> user = new List<string>();
user.Add(usertextBox.Text);
I want it where each time I press the button, whatever is in usertextBox at that point gets added to the list 'user' as a new item, so I can recall the different ones later with [1], [2], [3], etc. I also want it so the user can close the app and all the users will still be saved. I I don't know if C# does this automatically
Even if you can only answer one of my questions that's fine. Thanks!!
In your code you are making List local to Button that means every time you click button new object of List is created, You should create it out side button click method. Try this.
List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
You have to define the List out side of the method. C# does not keep the content of the list.
private List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
}
for saving the content you could use a database (http://msdn.microsoft.com/en-us/library/bb655884%28v=vs.90%29.aspx) or an xml file (http://www.codeproject.com/Articles/7718/Using-XML-in-C-in-the-simplest-way).
to save the content of the List you could create a new class containing this two methods instead of the list
public List<string> getListContent()
{
//read xml-file
}
public void Add(string t)
{
//write to xml file
}
This will just fine work in single thread applications.

Reload the combo box after insert query?

I want to reload the combo box so that it would display the values recently entered by me.
The Language used is C#.Net 2005..I am making a windows application. Please guide me?
you just need to call the method .DataBind() every time you want to "refresh" the combobox with new data
Save your last entered values, then load them when the comboBox is loaded. Something like:
private stirng _comboBoxSavedListPath = "";//or from application settings..
private List<string> _comboBoxLastEnteredValues = new List<string>();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)//or whenever you want to save
{
if (comboBox1.SelectedIndex > -1)
{
string entry = comboBox1.SelectedItem.ToString();
if (!_comboBoxLastEnteredValues.Contains(entry))
{
_comboBoxLastEnteredValues.Add(entry);
}
}
}
Now handle the form Closing event or just save the list again whenever item added. and load the list whenever form is loaded:
private void form1_Closing..
{
SaveList(_comboBoxLastEnteredValues);//Like(File.WriteAllLines(_comboBoxLastEnteredValues.ToArray(), _comboBoxSavedListPath);
}
private void form1_Load...
{
_comboBoxLastEnteredValues = LoadLastSavedList();//Like File.ReadAllLines(_comboBoxSavedListPath);
}

Categories