Getting value of selected item in list box as string
If you want to retrieve the display text of the item, use the GetItemText
method:
string text = listBox1.GetItemText(listBox1.SelectedItem);
How to get listbox selected item value
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName
with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.
Getting the text value selected in at ListBox in C#
As indicated by Charles May, your XAML shows that your ListBox is within another ListBox, which is why you're getting errors being raised..
The event being called "ListBox_SelectionChanged_1" is bound to the ListBox object inside ListBox1, which is unnamed.
I believe that the behaviour you are looking for would be fixed like this:
XAML:
<Label Content="Report" HorizontalAlignment="Left" Height="47" Margin="36,75,0,0" VerticalAlignment="Top" Width="63"/>
<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="121" Margin="84,75,0,0" VerticalAlignment="Top" Width="102" SelectionChanged="ListBox_SelectionChanged" SelectedIndex="-1">
<ListBoxItem x:Name="ListBoxFAT" Content="FAT"/>
<ListBoxItem x:Name="ListBoxNUMI" Content="NUMI"/>
<ListBoxItem x:Name="ListBoxSSID" Content="SSID"/>
<ListBoxItem x:Name="ListBoxFact" Content="FACT"/>
</ListBox>
Code Behind:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ListBox)?.SelectedItem as ListBoxItem)?.Content.ToString();
MessageBox.Show(text);
}
Or at least something close to this solution.
Getting text as string from selected item in ListBox
You can get the name like this in the selectionchanged event,
private void phoneListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Thing lbi = ((sender as ListBox).SelectedItem as Thing);
string selected = lbi.Name.ToString();
}
Getting selected item from a listbox
Don't add the string builder to the list, that's an object reference to an object collection. Use the ToString()
method (as you have commented out)
See this example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++)
{
builder.Append(i);
listBox1.Items.Add(builder);
builder.Clear();
}
for (int i = 0; i < 10; i++)
{
builder.Append(i);
listBox2.Items.Add(builder.ToString());
builder.Clear();
}
}
private void button2_Click(object sender, EventArgs e)
{
string a = listBox1.GetItemText(listBox1.SelectedItem.ToString());
string b = listBox1.SelectedItem.ToString();
string c = listBox1.GetItemText(listBox1.SelectedItem);
string d = listBox2.GetItemText(listBox2.SelectedItem.ToString());
string f = listBox2.SelectedItem.ToString();
string g = listBox2.GetItemText(listBox2.SelectedItem);
MessageBox.Show("1:" + a + b + c + "\r\n2: " + d+ f + g);
}
}
}
How to retrieve selected values for selected items in a ListBox?
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);
Passing selected item in listbox as a string to another page
What you get in AnyList.SelectedItem is based on type of its ItemsSource. You need to change this line :
string ListBoxConent = ((ListBoxItem)AnyList.SelectedItem).Content.ToString();
to this :
string ListBoxConent = ((MainViewModel.Search)AnyList.SelectedItem).ByAny;
How can I read the SelectedItem of a Listbox?
Your description is somewhat upside-down.
It's not clear whether you want to set a ListBox.SelectedItem
using the Text of a TextBox
or you want to set a TextBox.Text
with the text of the SelectedItem
of a ListBox.
The code says one thing, the description another. The error you have is probably caused by a null SelectedItem
(you haven't selected anything).
But, if you want to set a TextBox.Text
with the ListBox.SelectedItem
text, you can use the GetItemText() method. This method has a plus, it won't raise an exception if the Listbox has no selected Items (the SelectedItem is null
(nothing
)).
TextBox1.Text = ListBox1.GetItemText(ListBox1.SelectedItem)
The opposite:
You can use the ListBox FindString() and FindStringExact() methods to locate an item in the control's collection corresponding to a given string.
The former finds the first items in the ListBox that starts with the specified string, the latter matches only the whole string.
The search can begin from a specific index. It's not case sensitive.
listBox1.SelectedIndex = listBox1.FindString(textBox1.Text, 0)
' or
listBox1.SelectedIndex = listBox1.FindStringExact(textBox1.Text, 0)
You can continue the search specifying, as the starting point, the index of the item previously found:
private int lboxSearchIndex = -1;
Private Sub ButtonSearch_Click(sender As Object, e As EventArgs) Handles ButtonSearch.Click
lboxSearchIndex = listBox1.FindString(textBox1.Text, lboxSearchIndex)
listBox1.SelectedIndex = lboxSearchIndex
End Sub
Setting the SelectedItem
is like using the FindStringExact()
method.
Only a full match will set the item, but it's case sensitive.
Get listbox SelectedItem string when using Display/Value Member
You can use GetItemText
from the SelectedItem
:
Dim picturePath As String = MyListBox.GetItemText(MyListBox.SelectedItem)
From MSDN:
If the
DisplayMember
property is not specified, the value returned by
GetItemText
is the value of the item'sToString
method. Otherwise, the
method returns the string value of the member specified in the
DisplayMember
property for the object specified in the item parameter.
If nothing is selected GetItemText
returns an empty string. So if you want to handle that in a different way you should first check if SelectedIndex <> -1
or SelectedItem IsNot Nothing
.
Listbox.items[i].Selected only captures the first selected item
Make sure you have set the SelectionMode correctly to allow multiple item selection.
Then, for a multi-selection ListBox, you can use SelectedItems to get a collection of all the selected items.
Your code could be re-written as:
string selectedItem = "";
foreach (var s in impactedServicesData.SelectedItems)
{
if (selectedItem == "")
{
selectedItem = s.Value;
}
else
{
selectedItem += "," + s.Value;
}
}
Also consider using a StringBuilder when concatenating many strings in a loop.
Related Topics
Restsharp Serializing Json Objects to Post Parameters
Asp.Net Core Form Post Results in a Http 415 Unsupported Media Type Response
Asp.Net Core Get Json Array Using Iconfiguration
Redirecting to Another Page in ASP.NET MVC Using Javascript/Jquery
How to Determine If a Json Object Contains Only a Specific Key
How to Remove Windows Credentials
Passing Datetimeoffset as Webapi Query String
Reference External Dll in .Net Core Project
Asp.Net Core, Change Default Redirect for Unauthorized
Kill Child Process When Parent Process Is Killed
Setting Connection String With Username and Password in Asp.Core MVC
Replace Single Backslash With Double Backslash
How to Validate a Datetime in C#
Console.Writeline Does Not Show Up in Output Window
Getting Error Message Box When Textbox1.Text Is Empty