Trying to populate textbox and listview from txt file - c#

I'm able to save the textbox text and the listview items to a txt file properly by using:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
//writer.WriteLine(accountText.Text);
writer.WriteLine(accountText.Text);
if (transactionList.Items.Count > 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder newString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
newString.Append(string.Format("{0}\t", listSub.Text));
}
writer.WriteLine(newString.ToString());
}
writer.WriteLine();
}
}
}
}
However, I'm only able to load the textbox and can't seem to get the listview to populate. Here's what I have for that so far:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
if (transactionList.Items.Count == 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder myString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
}
reader.Read();
}
reader.ReadToEnd();
}
}
}
}
Any tips would be appreciated.

You just need to split string by '\t' character, it will return string[]. Then just add these array items to listview.
string[] items = reader.ReadLine().Split('\t');
foreach (var item in items)
{
var listViewItem = new ListViewItem(item);
transactionList.Items.Add(listViewItem);
}

As far as I can tell you're not putting the string into the ListView.
You will want to to do something like this:
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
listSub.Text = myString.ToString();
}

You need to reverse all your actions while reading
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
while(!reader.EndOfStream)
{
var myString = reader.ReadLine();
var subitems = myString.Split("\t");
// Create ListItem and assign subItems here...
transactionList.Items.Add(new ListviewItem(subitems));
}
}
}
}
}

Related

How to convert listbox.items to a Array

I'm making a search function for a ListBox, and I would like that as soon as the user types something into a TextBox, all items are removed from the ListBox except the item that matches the search text.
//files[i] are the files of the openfiledialog
List<String> ListboxItems = new List<String> {files[i]};
try
{
String search = gunaTextBox1.Text;
if (String.IsNullOrEmpty(search))
{
listBox1.Items.Clear();
listBox1.Items.AddRange(ListboxItems.ToArray());
}
var items = (from a in ListboxItems
where a.StartsWith(search)
select a).ToArray<String>();
listBox1.Items.Clear();
listBox1.Items.AddRange(items);
}
catch { }
Does anyone know how I can implement this?
Here is the solution
first you need to add a List String List<string> listcollection = new List<string>();
then you need to write the Textbox1_TextChanged event
List<string> listcollection = new List<string>();
private void gunaTextBox1_TextChanged(object sender, EventArgs e)
{
if(gunaTextBox1.Text == "Suche")
{
}
else
{
try
{
String search = gunaTextBox1.Text;
if (String.IsNullOrEmpty(search))
{
listBox1.Items.Clear();
listBox1.Items.AddRange(listcollection.ToArray());
}
var items = (from a in listcollection
where a.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1
select a).ToArray<String>();
listBox1.Items.Clear();
listBox1.Items.AddRange(items);
}
catch
{
}
}
}
and then just link it up
listcollection.Clear();
foreach(string str in listBox1.Items)
{
listcollection.Add(str);
}

Add List<string> to DataGridView Rows

I am new to using the DataGridView component, I've used it once before and have managed to complete this exact task but I forgot how I achieved it.
Basically I would like to read the values from a text file which is formatted like so:
line 1,
line 2,
line 3
Here is the code I currently have:
List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}
The current code results in the line 2 being added to the datagridview only, with nothing else.
I would like to add each line into the first column of each row, depending on how many lines are in the text file.
Hopefully this makes sense, thanks a lot!
You can try this:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}

Saving ListView into Properties.Settings.Default

I have build this C# for LOADING and SAVING items and subitems from a ListView:
private void Form1_Load(object sender, EventArgs e) {
this.Location=Properties.Settings.Default.FormLocation;
if (Properties.Settings.Default.AllePcer == null) {
Properties.Settings.Default.AllePcer = new StringCollection();
}
var items = new ListViewItem[Properties.Settings.Default.AllePcer.Count];
for (int i = 0; i < items.Length; i++) {
items[i] = new ListViewItem(Properties.Settings.Default.AllePcer[i].Split('|'));
}
this.listView1.Items.AddRange(items);
this.Show();
butten_Help.Focus();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
Properties.Settings.Default.FormLocation=this.Location;
Properties.Settings.Default.AllePcer = new StringCollection();
var items = new List<string>();
foreach (ListViewItem item in this.listView1.Items) {
List<string> subitems = new List<string>();
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems) {
subitems.Add(subitem.Text);
}
items.Add(string.Join("|", subitems)); <<<<<<<<<<<<<<<<<<<<
}
Properties.Settings.Default.AllePcer.AddRange(items.ToArray());
Properties.Settings.Default.Save();
}
The line with the "<<<<<<<<<<<<<<<<<<" gives me compilingerror:
cannot convert from 'System.Collections.Generic.List' to
'string[]'
How can I correct this ?

C# Loadl List into textbox WinForms

I have a problem when I try to display the list into the textbox. It only displays the last line from the list.txt file. I think for each new line it overwrites the first line from the textbox all the time ? thus showing only the last line from the file ?
what is it I need to think of to get it right ?
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
}
Instead of this:
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
Try:
textBox1.Text = string.Join(Environment.NewLine, myList);
And also make sure multiline property of textbox1 is set to true.
Because every time, you assign directly to the Text property which will remove the previous one . Here is the fix . Make Multiline of textbox true.
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
var listString = new StringBuilder()
foreach (string s in myList)
{
listString.Append(Environment.Newline)
listString.Append(s);
}
textBox1.Text = listString.ToString();
}
Based on my comment you can do this in one simple line by eliminating the foreach loop
textBox1.Text = string.Join(Environment.NewLine, myList.ToArray());
or just use the myList works the same
textBox1.Text = string.Join(Environment.NewLine, myList);

C# nullReferenceException while adding items to array

I get this error when I try to add items to an array, it adds with no problem 1 items, but when there are more it stops and gives an error.
nullReferenceException
Object reference not set to an instance of an object.
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
OpenFiles[index] = new AddFileClass();
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}
here is a pic to show that the fi(FileInfo) and di(DirectoryInfo) are not empty:
It looks to me that you never initialize the OpenFiles array items - that is, you only initialize the first item.
Try this:
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index] = new AddFileClass();
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}

Categories

Resources