Get text of selected items in a ListBox - c#

I'm trying to show the selected items of listBox1 in a Message Box here's the code:
int index;
string item;
foreach (int i in listBox1 .SelectedIndices )
{
index = listBox1.SelectedIndex;
item = listBox1.Items[index].ToString ();
groupids = item;
MessageBox.Show(groupids);
}
The problem is that when I select more than one item
the message box shows the frist one I've selected and repeats the message
EX: if I selected 3 items the message will appear 3 times with the first item

You can iterate through your items like so:
foreach (var item in listBox1.SelectedItems)
{
MessageBox.Show(item.ToString());
}

The i in the foreach loop has the index you need. You're using listBox1.SelectedIndex which only has the first one. So item should be:
item = listBox1.Items[i].ToString ();

How about 1 message box with all the selected items?
List<string> selectedList = new List<string>();
foreach (var item in listBox1.SelectedItems) {
selectedList.Add(item.ToString());
}
if (selectedList.Count() == 0) { return; }
MessageBox.Show("Selected Items: " + Environment.NewLine +
string.Join(Environment.NewLine, selectedList));
If any are selected, this should give you a line for each selected item in your message box. There's probably a prettier way to do this with linq but you didn't specify .NET version.

Try this solution:
string item = "";
foreach (int i in listBox1.SelectedIndices )
{
item += listBox1.Items[i] + Environment.NewLine;
}
MessageBox.Show(item);

Related

Converting list box Items to a String C#

I'm writing a WPF application. How to Convert ListBox items to single string Value?
I have 1 Text Box, an ADD Button to add items to a List Box, and a SAVE Button to SAVE items in Console Window.
How can I do this?
//Concatenation of all items of list box
string allItems = string.Join(", ",listBox1.Items.OfType<object>());
//Concatenation of selected tiems of list box
string selectedItems= string.Join(", ",listBox1.SelectedItems.OfType<object>());
var listboxitems = listbox1.Items.Cast<ListBoxItem>().Select(p => p.Content as string);
string result= String.Join("|", listboxitems .ToArray());
This will place
value1|value2|value3
On which ever Button Click you want to Convert that Items to single String value Add this piece of code :
Stringbuilder sb =new StringBuilder();
private void btn1_Click(object sender, RoutedEventArgs e)
{
//Suppose that ListBox name is listBox1
for(int i=0;listBox1.Items.Count; i++)
{
sb.Append(listBox1.Items[i].ToString());
}
}
use this Stringbuilder sb.ToString() to Your Text box
txtname.text =sb.ToString();
ListBox listBox1 = new ListBox();
for (int x = 1; x <= 5; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
StringBuilder sb = new StringBuilder();
foreach (var item in listBox1.Items)
{
sb.Append(item.ToString());
}
Console.WriteLine(sb.ToString());
You can simply try:
string[] listAsArray = listBoxPart.Items.OfType<string>().ToArray();
Add a new string content from your TextBox:
Assume that you have a TextBox name textBox,
You can get string content of the textBox by Text property.
You have to create 2 Button (s).
Button ADD: To add the string from your TextBox to your ListBox
Button SAVE: To save the ListBox items to a Console Window
See the code:
ListBoxItem item1 = new ListBoxItem();
item1.Content = textBox.Text;
listBox.Items.Add(item1);
// Do the same with item2, item 3,... item n
Show in a Console Window:
foreach (var item in listBox.Items)
{
Console.WriteLine(item);
}

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);
}
}

Why my "foreach" C# code doesn't loop through all items in listBox?

What is expected: tool to do task on each item, one by one in the listbox.
What is happening: tool does the task only on the user selected item in the listbox. And nothing else.
Code:
int index;
string item;
foreach (int i in listBox1.SelectedIndices)
{
index = listBox1.SelectedIndex;
item = listBox1.Items[index].ToString();
texteditor.Documents.Open(#item);
}
this should iterate through all items
foreach (var item in listBox1.Items)
{
texteditor.Documents.Open(item.ToString());
}
You are iterating over selected items, whereas you want to interate over all the items in your list box.
Also, the correct way to iterate over a ListBox returns a ListItem and not an int.
Try this:
string item;
foreach (ListItem li in listBox1.Items)
{
item = li.ToString();
texteditor.Documents.Open(#item);
}
I also removed the index variable from your code. If you needed the index for something else you would need a for loop like this:
string item;
for (int index = 0; index < listBox1.Items.Count; index++) {
item = listBox1.Items[index].ToString();
texteditor.Documents.Open(#item);
// do something with index
}

Why when adding items to combobox it's adding the same item many times?

In the top of form1:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
List<string> results = new List<string>();
Then:
ComboboxItem item = new ComboboxItem();
var result = videoCatagories.Execute();
for (int i = 0; i < result.Items.Count; i++)
{
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
And in the end:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
What i wanted to do in general is to add to the combobox the titles and then when i select a title to get the title id.
For example i run the program and select the title Weather now i want to see in a messageBow.Show the id 1
There are 31 items.
When i use a breakpoint and look on result i see 31 items when i click on the first item in index 0 i see Id = "1" and then i click on snippet and see title "weather"
Then i do the same for item in index 1 and i see Id = "19" and in the snippet the title is "animals".
But for some reason it's adding each itertion the same item many times.
Create a new instance of ComboboxItem each time you want to add a new item to the combo box:
for (int i = 0; i < result.Items.Count; i++)
{
ComboboxItem item = new ComboboxItem();
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
Your code changes the properties of the same item instance for each entry in results, then adds it to the comboBox1.Items collection. Add inserts its argument to the Items collection, it doesn't copy its contents. As a result, when the combobox is rendered, all combobox items point to the same item. To avoid this, create a new item instance for each entry in results:
for (int i = 0; i < result.Items.Count; i++)
{
var item=new ComboboxItem
{
Text = result.Items[i].Snippet.Title,
Value = result.Items[i].Id
};
comboBox1.Items.Add(item);
}
or
var items=from item in result
select new ComboboxItem
{
Text = item.Snippet.Title,
Value = item.Id
};
comboBox1.Items.AddRange(items);
You could do a simple check to make sure that the combobox doesn't already contain it before doing the insert.
ComboboxItem item = new ComboboxItem();
var result = videoCatagories.Execute();
for (int i = 0; i < result.Items.Count - 1; i++)
{
if(!comboBox1.Items.Contains(item))
{
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
}
Or you can do like this article suggests and remove every item that is the same before adding the new item to remove conflicts, No Duplicate in a Listbox or using the same way to stop duplicates from a combobox too

listbox selectedindex only selecting last element

I have a listbox that is bound to a list of objects from the database. I have a secondary list that has less objects that I want to use it to mark as selected elements.
cell = new HtmlTableCell();
List<ClasaAutor> listaAutori = DataTableToClasaAutor(dal.CitesteTotiAutori());
List<ClasaAutor> listaAutoriPublicatie = DataTableToClasaAutor(dal.CitesteTotiAutoriUneiPublicatii(guidPublicatie));
ListBox list = new ListBox();
list.SelectionMode = ListSelectionMode.Multiple;
list.ID = "cbAutori";
list.DataSource = listaAutori;
list.DataTextField = "NumeComplet";
list.DataValueField = "GuidAutor";
list.DataBind();
foreach (ClasaAutor autor in listaAutoriPublicatie)
{
for (int i = 0; i < list.Items.Count; i++)
{
if (list.Items[i].Value == autor.GuidAutor.ToString())
list.SelectedIndex = i;
}
}
cell.Controls.Add(list);
row.Cells.Add(cell);
The problem is that only my last element gets selected... why? How can I fix it?
My if is ok, it gets true 2 times...
Try this loop:
foreach (ClasaAutor autor in listaAutoriPublicatie)
{
foreach (ListItem item in list.Items)
{
if (item.Value == autor.GuidAutor.ToString())
item.Selected = true;
}
}
the problem in semantics, SelectedIndex of list can hold only one value, this is not collection
however you could make list item selected by setting the Selected value of it to true
list.Items[i].Selected = list.Items[i].Value == autor.GuidAutor.ToString();

Categories

Resources