Populating listview with List<List<string>> - c#

I'm coding in C# andI have a listview control with few columns, and I'm wondering, how can I add items to it from List<List<string>>. I am able to add items with
var item3 = new ListViewItem(new[] { table[0][0], table[0][1], table[0][2], table[0][3], table[0][5], table[0][7], table[0][8] });
but that doesn't seem right to me, and neither it would work because the amount of Lists is random.

You can use List<T>.ToArray to convert the list into an array which you then pass to the constructor of ListViewItem. As you are only interested in the first subitem of your table, you can just do it like this:
var item3 = new ListViewItem(table[0].ToArray());

You can use the following code to fill all the List<List<string>> into your ListView:
listView1.Items.AddRange(table.Select(list=>new ListViewItem(list.ToArray())))
.ToArray();

probably you mean like this ?
sample data
item1
List<string> list1 = new List<string>();
list1.Add("item-1.1");
list1.Add("item-1.2");
item2
List<string> list2 = new List<string>();
list2.Add("item-2.1");
list2.Add("item-2.2");
allitem
List<List<string>> listAll = new List<List<string>>();
listAll.Add(list1);
listAll.Add(list2);
string value
string sResult = string.Join(", ", from list in listAll from item in list select item);
list value
List<string> lResult = new List<string>(from list in listAll from item in list select item);
binding
lv.DataSource = lResult;
lv.DataBind();
result
item-1.1 item-1.2 item-2.1 item-2.2

Related

How to sort a listBox in C#?

I have typed numbers in a textbox and added them into a listBox. Now I need to order that listbox. This is my try:
int[] array = listBox1.Items.Cast<int>().ToArray<int>();
Array.Sort(array);
listBox1.Items.Clear();
foreach (int item in array)
{
listBox1.Items.Add(item);
}
It throws an 'System.InvalidCastException'. But I can't figure it out HOW to solve it.
You can use a lambda
var array = listBox1.Items.OfType<string>().Select(x => int.Parse(x))
.ToArray();
First, I want to say that it is not a good idea to store data inside a control. Always put your data inside types that can handle them like a List, Dictionary, etc. and then bind that to your listbox object. I guess you are working on windows forms. Then add a property to your form and put all your data in it.
something like this
public partial class Form1 : Form
{
List<string> _items = new List<string>(); // <-- Add this
public Form1()
{
InitializeComponent();
_items.Add("One"); // <-- Add these
_items.Add("Two");
_items.Add("Three");
listBox1.DataSource = _items;
}
public void add()
{
_items.Add("four");
_items.Sort();
}
}
This is as simple as
listBox1.Sorted = true;
UPDATE
var array = new object[listBox1.Items.Count];
listBox1.Items.CopyTo(array, 0);
listBox1.Items.Clear();
var sortedArray = array.Select(n => (object)Convert.ToInt32(n)).OrderBy(n => n).ToArray();
listBox1.Items.AddRange(sortedArray);
ListBox items can cast to string. So, You must cast it to string[], then convert to int[], then sort it and finally add sorted data to ListBox.
string[] strArray = listBox1.Items.Cast<string>().ToArray();
int[] intArray = strArray.Select(x => int.Parse(x)).ToArray();
Array.Sort(intArray);
listBox1.Items.Clear();
foreach (int item in intArray)
{
listBox1.Items.Add(item);
}
I hope this will be useful.

C# ListView to List<string>

I have a ListView with string items, and i am trying to get these items and store them in List container.
I need the reverse operation of this:
List<string> myList = new List<string> { "Item1", "item2", "item3"};
resultsList.ItemsSource = myList;
So my Question is How to Parse ListView with Items to List?
You need to cast it to IEnumerable<string>
List<string> myList = ((IEnumerable<string>)resultsList.ItemsSource).ToList();
I think you can cast and use ToList to create a list:
myList = resultsList.ItemsSource.Cast<string>().ToList();

match list view items against array list in c#

I have an ArrayList that contains some HashTables , and I have a ListView that contains some items.
What I need is to match the array list with the list items.
If an item in the list view and not in the array list, then it should be removed from the list view.
If not in either the list view or the array list, then add it to list view.
This is some code:
ArrayList online_list = users;
foreach (Hashtable i in online_list)
{
ListViewItem item = new ListViewItem();
item.Text = (string)i["u_name"];
item.Name = (string)i["id"];
item.ImageIndex = 0;
lstvUsers.Items.Add(item);
}
This code adds all array list items to the list view without the check!
You could first clear all items of the ListView, then add all in the ArrayList:
lstvUsers.Clear();
foreach (Hashtable i in online_list)
{
ListViewItem item = new ListViewItem();
item.Text = (string)i["u_name"];
item.Name = (string)i["id"];
item.ImageIndex = 0;
lstvUsers.Items.Add(item);
}
You should use ListView.Clear instead of ListView.Items.Clear: https://stackoverflow.com/a/10170049/284240
Edit: Since you're adamant that you only want to remove items from the ListView that are not in the ArrayList and add items that are not in the ListView but in the ArrayList . That approach is significantly less efficient since you need to compare each item in the ListView with each item in the ArrayList (and vice-versa) instead of comparing nothing.
For example:
var addItems = online_list
.Cast<Hashtable>()
.Where(ht => !lstvUsers.Items.ContainsKey((string)ht["id"]));
var removeItems = lstvUsers.Items
.Cast<ListViewItem>()
.Where(lvi => !online_list.Cast<Hashtable>().Any(ht => (string)ht["id"] ==lvi.Name));
foreach (var removeItem in removeItems)
{
lstvUsers.Items.Remove(removeItem);
}
foreach (var addHashTable in addItems)
{
ListViewItem item = new ListViewItem();
item.Text = (string)addHashTable["u_name"];
item.Name = (string)addHashTable["id"];
lstvUsers.Items.Add(item);
}

Need to copy items from one listbox to another listbox using a session variable

Page 1: (sending listbox items into a list and saving the list as a session variable)
List<string> list = new List<string>();
foreach(ListItem item in ListBox1.Items)
{
list.Add(item.ToString());
}
Session["temp"] = list;
Page 2: (copying the session variable into a list and assigning the list to a listbox in this page)
List<string> list = new List<string>();
list = (List<string>)Session["JobRole"];
foreach (ListItem item in list)
{
ListBox2.Items.Add(item.ToString());
}
On doing so, this is the error i m getting : Cannot convert type 'string' to 'System.Web.UI.WebControls.ListItem'
can anyone pls help me with this ??
Thanks
Don't you mean
foreach (string item in list)
{
ListBox2.Items.Add(item);
}
... list is a list of strings after all.
That's because you have defined list as List. If you simply want to add the string value into the listbox you can do:
List<string> list = new List<string>();
list = (List<string>)Session["JobRole"];
foreach (string item in list)
{
ListBox2.Items.Add(item);
}
Also you should check that Session["JobRole"] is not null.

Cannot convert SelectedObjectCollection to ObjectCollection ?

I am trying to get a list of all elements from ListBox if no or one of items is selected or list of selected items if more than 1 are selected. I have written such a code but it doesn't compile :
ListBox.ObjectCollection listBoXElemetsCollection;
//loading of all/selected XMLs to the XPathDocList
if (listBoxXmlFilesReference.SelectedIndices.Count < 2)
{
listBoXElemetsCollection = new ListBox.ObjectCollection(listBoxXmlFilesReference);
}
else
{
listBoXElemetsCollection = new ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
}
So for this piece of code to work I would need to use something like ListBox.SelectedObjectCollection listBoxSelectedElementsCollection; which I do not want because I would like to use it in such an foreach:
foreach (string fileName in listBoXElemetsCollection)
{
//...
}
I'd simply this a bit and not mess with the ListBox ObjectCollections if you don't need to. Since you want to iterate items on your ListBox as strings, why not use a List and load the list how you show:
List<string> listItems;
if (listBoxXmlFilesReference.SelectedIndices.Count < 2) {
listItems = listBoxXmlFilesReference.Items.Cast<string>().ToList();
} else {
listItems = listBoxXmlFilesReference.SelectedItems.Cast<string>().ToList();
}
foreach (string filename in listItems) {
// ..
}
You need to convert SelectedObjectCollection to an array of object[].
ListBox.SelectedObjectCollection sel = new
ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
ListBox.ObjectCollection col = new
ListBox.ObjectCollection(listBoxXmlFilesReference,
sel.OfType<object>().ToArray());
I can see what you're trying to do and it doesnt compile because the type ListBox.ObjectCollection is not the same as ListBox.SelectedObjectCollection - even though in your case they are lists that contain strings the classes themselves are different hence the compile error.
Assuming your items are strings in the listbox you could do:
var items = listBoXElemetsCollection.Items.OfType<string>();
if (listBoXElemetsCollection .SelectedIndices.Count >= 2)
items = listBoXElemetsCollection.SelectedItems.OfType<string>();
foreach(var item in items)
//do stuff

Categories

Resources