Store elements from a ListView into a List - c#

Since I haven't found anything that helped, I ask my question here:
I have a ListView where I select a whole row by click. Now I want to store these selected items into a List but don't know how this should work exactly.
List<String> itemSelected = new List<String>();
foreach (var selectedRow in listView1.SelectedItems)
{
itemSelected.Add(selectedRow);
}
That doesn't work because I need an index (selectedRow[?]) or something like that. How can I store the values of the first column when clicked the row?
EDIT: The problem is that the ListViewItems have the type "object"
The ListView gets populated this way:
using (SqlConnection connection = new SqlConnection(connectionQuery))
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
col1 = row.Cells[col1.Text].Value.ToString();
col2 = row.Cells[col2.Text].Value.ToString();
col1Cells.Add(col1);
col2Cells.Add(col2);
}
}

You can do something like:
ListViewItem listViewItem = this.listView1.SelectedItems.Cast<ListViewItem>().FirstOrDefault();
if (listViewItem != null)
{
string firstColumn = listViewItem.Text;
string secondColumn = listViewItem.SubItems[0].Text;
// and so on with the SubItems
}
If you have more selected items and only need the values of the first columns you can use:
List<string> values = listView1.SelectedItems.Cast<ListViewItem>().Select(listViewItem => listViewItem.Text).ToList();

It's common to bind a ListView to the List of non-trivial types.
Then you can handle SelectedItemChanged or something like that. You receive the whole object (in type object) which you can cast to your custom type and retrieve any properties you want

Related

How to retrieve selected values for selected items in a ListBox?

I'm populating a ListBox in a WinForms application, this way:
listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";
how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple
I want to do a foreach loop on them, like this:
foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
int id = int.Parse(itemId);
// . . .
}
Since you know the type of items, you can use such code:
var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:
var selectedValues = listBox1.SelectedItems.Cast<object>()
.Select(x => listBox1.GetItemValue(x)).ToList();
If for some reason you are interested to have a text representation for selected values:
var txt = string.Join(",", selectedValues);
Have you tried with the SelectedItems property?
foreach (var item in listBoxUsers.SelectedItems)
{
}
try this:
foreach (DataRowView item in listBoxUsers.SelectedItems)
{
int id=int.parse(item[0].ToString());
}

ListBox multiple Selection get all selected values

I'm having a problem since a while now an just can't find any solution that works for me. I have a ListBox which is filled up with a DataTable like
listbox.DataSource = table;
listbox.Displaymember = "Name";
listbox.ValueMember = "ID";
If I now select an item in my listbox I can get it out like:
listbox.SelectedValue.toString();
My Problem:
What can I do if I would like to have ALL selected Values from a ListBox where multiple selection is enabled and save them all in an array or something like that?!
I can't use SelectedItems cause that is not giving me the information I need.
Try this:
var lst = listBox1.SelectedItems.Cast<DataRowView>();
foreach (var item in lst)
{
MessageBox.Show(item.Row[0].ToString());// Or Row[1]...
}
Or if you want only iterate over the selected items you can use SelectedIndices property:
foreach (int i in listbox.SelectedIndices)
{
// listbox.Items[i].ToString() ...
}
Or:
foreach (var item in listbox.SelectedItems)
{
MessageBox.Show(item.ToString());
}

How to delete multiple rows in a table that are selected in a listbox?

I have a table which's content is displayed at listbox. I want to delete rows that user has selected. How to know which rows to delete and how delete?
This is how I display listbox items:
DataSet AllPairs = new DataSet();
AllPairs.ReadXml(PathToPairsXML);
listBox1.DataSource = AllPairs.Tables[0];
listBox1.ValueMember = "PAIR_text";
listBox1.DisplayMember = "PAIR_text";
Listbox selection property is MultiExtended.
When you use DataTable as DataSource of your ListBox, items are of type DataRowView, so you can use Delete method of DataRowView or using Row property of DataRowView access the row behind that data row view and remove that row from your DataTable.
You can use this code:
this.listBox1.SelectedItems.Cast<DataRowView>()
.ToList()
.ForEach(item =>
{
//item.Delete();
//or
this.AllPairs.Tables[0].Rows.Remove(item.Row);
});
string selectedtext= "";
foreach (int i in listBox1 .SelectedIndices )
{
selectedtext= listBox1.Items[i].ToString ();
DataRow[] drCollection=AllPairs.Tables[0].Select("PAIR_text='"+selectedtext+"'");
if (drCollection.Length>0)
AllPairs.Tables[0].Rows.Remove(drCollection[0]);
}
This is so far the simplest way:
var selectedRows = listBox1.SelectedItems.Cast<DataRowView>().ToList();
foreach (var dr in selectedRows)
dr.Delete();
A small explanation. I'll be using the concrete types instead of var keyword for better understanding. The following line
listBox1.DataSource = AllPairs.Tables[0];
in equivalent to something like this
DataView dataView = AllPairs.Tables[0].DefaultView;
for (int i = 0; i < dataView.Count; i++)
{
DataRowView dataRowView = dataView[i];
listBox1.Items.Add(dataRowView);
}
Now when we know the list box contains DataRowView objects, although the SelectedItems returns items of type object, we can safely cast them back to a DataRowView and call Delete method.
But why we need ToList call? Because when we delete a row, the data source will send a notification to the list box and it will remove that item from the Items and SelectedItems. While it's not required, depending of the internal implementation this could destroy the selection. So in order to be absolutely sure that this will not happen, we buffer the initial selection in a list before proceeding with delete.

Retrieve comboBox displayed values

I am trying to retrieve the displayed values of all items present in a comboBox.
First case: if the comboBox has been filled using a DataSource:
comboBox.DataSource = myDataSet.Tables[0];
comboBox.DisplayMember = "value";
comboBox.ValueMember = "id";
...I use this code:
foreach (DataRowView rowView in comboBox.Items) {
String value = rowView.Row.ItemArray[1].ToString();
// 1 corresponds to the displayed members
// Do something with value
}
Second case: if the comboBox has been filled with the comboBox.Items.Add("blah blah"), I use the same code, except I have to look in the first dimension of the ItemArray:
foreach (DataRowView rowView in comboBox.Items) {
String value = rowView.Row.ItemArray[0].ToString();
// 0 corresponds to the displayed members
// Do something with value
}
Now I would like to be able to retrieve all values without knowing the scheme used to fill the comboBox. Thus, I don't know if I have to use ItemArray[0] or ItemArray[1]. Is it possible? How could I do that?
You can try something like this:
string displayedText;
DataRowView drw = null;
foreach (var item in comboBox1.Items)
{
drw = item as DataRowView;
displayedText = null;
if (drw != null)
{
displayedText = drw[comboBox1.DisplayMember].ToString();
}
else if (item is string)
{
displayedText = item.ToString();
}
}
The Combobox would be populated with the DataSource property in the first case. Therefore its DataSource won't be null. In the second case, it would be null. So you could do an if-else with (comboBox1.DataSource==null) and then accordingly use ItemArray[0] or ItemArray[1].
Leito, you could check to see if the DataSource is a DataTable or not to determine which action to take.
if (comboBox.DataSource is DataTable)
{
// do something with ItemArray[1]
}
else
{
// do something with ItemArray[0]
}

Select the specific column of ListView and print it in a new messagebox in C#.net

I've just started to use ListView in C#.net.
I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.
I want to know how to do this.
I found this code to list a specific selected data from a row:
ListView.SelectedIndexCollection sel = listView1.SelectedIndices;
if (sel.Count == 1)
{
ListViewItem selItem = listView1.Items[sel[0]];
MessageBox.Show(selItem.SubItems[2].Text);
}
That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?
private string[] GetListViewItemColumns(ListViewItem item) {
var columns = new string[item.SubItems.Count];
for (int column = 0; column < columns.Length; column++) {
columns[column] = item.SubItems[column].Text;
}
return columns;
}
I would recommend some caution against doing this. A ListView is really meant to display information, it is not a great collection class. Getting the data out of it is slow and crummy, it can only store strings. Keep the data in your program in its original form, maybe a List<Foo>. Now it is simple and fast.
foreach (ListViewItem item in listView1.Items) {
// Do something with item
}
you could do this by
foreach(ListViewItem item in listView1.Items)
{
foreach(var subtem in item.SubItems)
{
// Do what ever you want to do with the items.
}
}

Categories

Resources