How to create listView from text file? - c#

I have a text file like this:
==
a
03/09
==
b
02/09
And I want to create a listView from the text file like this:
How can I do this in C#?
I've tried this code:
ListViewItem lvi = new ListViewItem();
var sectionCharacters = File.ReadLines("bdaylist.list")
.SkipWhile(s => s != "==")
.Skip(1)
.Skip(2)
.ToList();
lvi.Text = sectionCharacters[1];
lvi.SubItems.Add(sectionCharacters[2]);
listView1.Items.Add(lvi);
but it only read b and 02/09

You can try this:
var sectionCharacters = File.ReadLines("your_filepath_here").ToList();
//To remove '=='
sectionCharacters.Where(i => i.Trim() == "==").ToList()
.ForEach(item => sectionCharacters.Remove(item));
//To remove 'blank lines', if any
sectionCharacters.Where(i => i.Trim() == "").ToList()
.ForEach(item => sectionCharacters.Remove(item));
for (int i = 0; i < sectionCharacters.Count; i += 2)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = sectionCharacters[i];
lvi.SubItems.Add(sectionCharacters[i + 1]);
listView1.Items.Add(lvi);
}
Output:
PS: This is a simple listView to show the output. You might get the idea what to do with your listView having checkboxes.

You are using Skip(1) and Skip(2) which is ignoring your first 2 entries. You are also only adding one item to the list. You can change your linq as below, and check for the even number item in the collection to add both to the listview.
var sectionCharacters = File.ReadAllLines("bdaylist.list").Where(s => s != "==").ToList();
for (int i = 0; i < sectionCharacters.Count; i++)
{
if (i % 2 == 0)
{
var lvi = new ListViewItem { Text = sectionCharacters[i] };
lvi.SubItems.Add(sectionCharacters[i + 1]);
listView1.Items.Add(lvi);
}
}

Related

Delete Multiple Items from ObservableCollection

I want to delete multiple items in an ObservableCollection in C#. My code is:
var item = (MoveDataModel)e.SelectedItem;
var answer = await DisplayAlert("Confirmation", "Are you sure you wish to delete " + item.value + "?", "Yes", "No");
if (answer)
{
var type = item.type;
var value = item.value;
foreach (var listItem in items)
{
if ((listItem.value == item.value) || (listItem.location == value && type == "Location"))
{
items.Remove(listItem);
itemCount--;
}
}
}
The first iteration works fine. However, it hangs on
foreach (var listItem in items)
on the second pass. I'm not sure how to make it work.
you can't modify a collection while you're iterating over it. Try something like this (I haven't checked the syntax, may need some cleanup)
var removeList = items.Where(x => x.value == value).Where(y => y.type = type).ToList();
foreach(var i in removeList) {
items.Remove(i);
itemCount--;
}
Have your own counter, cycle backwards through the list so you wont have to readjust for indexes you removed.
System.Collections.ObjectModel.ObservableCollection<object> list = new System.Collections.ObjectModel.ObservableCollection<object>();
private void RemoveStuff()
{
var i = list.Count - 1;
for (; i <= 0; i--)
{
// some checks here to make sure this is the time you really want to remove
list.Remove(i);
}
}

Write first and second column rows in listview inside each row in a text file

I'm using WinForms. In my form I have a listview and a button. When I click on the button the program writes all of the items in the listview into a text file. The problem is that I want the first and second column to be in one line.
Here is my code so far that i use to write to the text file:
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.WriteLine(item.Text);
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
My ListView
Problem output text file
How I want the text file to display
How about just
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(item.Text + ": ");
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
It seems that your first cell "FirstPage" is the parent and all other items are sub items. Assuming you have only two columns below answer will work.
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(string.Format("{0} :",item.Text));
for (int i = 1; i < item.SubItems.Count; i++)
{
if (i % 2 == 0)
{
sw.Write(string.Format("{0} :",item.SubItems[i].Text));
}
else
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
}
Alternative is; add each new row as a new item to the list view
string[] row = { "FirstPage", "$1.00" };
string[] row2 = { "SecondPage", "$1.00" };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
var listViewItem2 = new ListViewItem(row2);
listView1.Items.Add(listViewItem2);
and so on. You can iterate through a foreach loop for this adding and then use the below code which is flexible.
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(string.Format("{0} :",item.Text));
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
You can do it in a more elegant way:
var str = listView1.Items.Cast<ListViewItem>()
.Select(x => x.SubItems.Cast<ListViewItem.ListViewSubItem>())
.Select(x => string.Join(":", x.Select(s => s.Text)));
System.IO.File.WriteAllLines(#"d:\file.txt", str);
Note: If you want to limit the columns for example save only first two columns, you can select sub items at second line this way: x.SubItems.Cast<ListViewItem.ListViewSubItem>().Take(2)
You should iterate the List View items, concatenate each one of the sub items into each other and then add the concatenated string to the text file at the end... I have adapted your code:
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
string strText = "";
//I'm not sure why you start at 1 and not 0, anyway:
for (int i = 1; i < item.SubItems.Count; i++)
{
strText+= " " + item.SubItems[i].Text;
}
sw.WriteLine(strText);
}
}

Change text in multiple textboxes?

How would I go about making a for loop that changes the text in more than 1 textbox?
for (int i; i < 5; i++)
{
textbox(i).text = "something"
}
But I don't know how to get the I to represent the number after the textbox, does anyone know how to?
Store the textboxes in an Array and then loop over the array
for (int i; i < 5; i++)
{
textboxArray[i].text = "something"
}
You could use Controls.Find:
var txts = this.Controls.Find("textbox" + i, true); // true for recursive search
foreach(TextBox txt in txts)
txt.Text = "something";
or - if the TextBoxes are in the same container control(like the Form or a Panel)- with LINQ:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name == "textbox" + i);
foreach(TextBox txt in txts)
txt.Text = "something";
Actually you don't need the loop variable, you could also use String.StartsWith to get all:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name.StartsWith("textbox"));
foreach(TextBox txt in txts)
txt.Text = "something";
if you dont want to alter every textbox on your form just simply add them to a List:
List<TextBox> TextBoxes = new List<TextBox>();
TextBoxes.Add(This.TextBox1);
TextBoxes.Add(This.TextBox3):
then as others have suggested you could either linq or regular foreach the textboxes in the list
TextBoxes.Foreach(Textbox => TextBox.Text = "something");
or
foreach (TextBox r in TextBoxes)
{
r.Text = "something;
}

Clear contents of specific listview columns?

This is how I currently add info to my listview:
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
int totItems = Seq3.Count - 1;
if (PercentPopTolerance1.Count - 1 > totItems) totItems = PercentPopTolerance1.Count - 1;
for (int i = 0; i <= totItems; i++)
{
ListViewItem lvi = new ListViewItem();
string item1 = "";
string item2 = "";
if (Seq3.Count - 1 >= i) item1 = Seq3[i].ToString();
if (PercentPopTolerance1.Count - 1 >= i) item2 = PercentPopTolerance1[i].ToString();
lvi.SubItems.Add(item1);
lvi.SubItems.Add(item2);
listView2.Items.Add(lvi);
}
}
View of empty listview:
Now how would I clear the contents of any particular column? Say I want to add to column YYMM but before I do this, I want to clear that particular column. How would this be done?
You can clear column values like this
var items = listView1.Items;
foreach (ListViewItem item in items)
{
a.SubItems["YYWW"].Text = "";
}
You should specify a column by its name (a column corresponds to a subitem in a ListViewItem), note that this Name is not ColumnHeader.Name, I mean the corresponding ListViewSubItem.Name:
public void ClearColumn(string colName){
foreach(ListViewItem item in listView1.Items){
var cell = item.SubItems[colName];
if(cell != null) cell.Text = "";
}
}
The following code will work for ColumnHeader.Name passed in instead of ListViewSubItem.Name as the code above does:
public void ClearColumn(string columnHeaderName){
int i = listView1.Columns.IndexOfKey(columnHeaderName);
if(i == -1) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[i].Text = "";
}
}
You can try the following code to make it work for Text instead of Name:
public void ClearColumn(string colText){
if(listView1.Items.Count == 0) return;
var col = listView1.Columns.Cast<ColumnHeader>()
.Select((x,i)=>new{x,i})
.FirstOrDefault(a=>a.x.Text == colText);
if(col == null) return;
foreach(ListViewItem item in listView1.Items){
item.SubItems[col.i].Text = "";
}
}

How to cut, copy, paste any listview item in C#?

for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
}
}
This function simply deletes the selected item in listview.. but i want to cut it and paste it somewhere else.
It sounds like you want to remove the selected listitems and move them to another listview.
ListView sourceListView = new ListView();
ListView destListView = new ListView();
var selected = sourceListView.Items
.Cast<ListViewItem>()
.Where(x => x.Selected)
.ToList();
foreach (var item in selected)
{
sourceListView.Items.Remove(item);
destListView.Items.Add(item);
}

Categories

Resources