Reputation: 361
I have encountered an issue trying to get the SelectedItem
in a ListBox
. The Listbox
is datasource bound to the list further down my example.
listBox1.DisplayMember = "StringPosition";
listBox1.ValueMember = "StringPosition";
listBox1.DataSource = MatchList;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
MessageBox.Show(curItem);
}
When i run the program and select an item in the list rather than the MessaseBox
showing the SelectedItem
it shows the overridden ToString
method in my custom class. Now the custom ToString
method was just a leftover from the MSDN example and i don't actually need it. However even if i comment it out rather than the overridden ToString
it will simply display Parser.SectorBodies
which is my project namespace and the custom class. So how do i resolve this so i can get the selected item in my ListBox
static List<SectorBodies> MatchList = new List<SectorBodies>();
public class SectorBodies
{
public int MatchCount { get; set; }
public string StringPosition { get; set; }
public string SolarSystemFileComment { get; set; }
public string SolarSystemX { get; set; }
public string SolarSystemY { get; set; }
public string SolarSystemZ { get; set; }
public override string ToString()
{
return
" Position: " + StringPosition +
" Count: " + MatchCount;
}
}
Upvotes: 0
Views: 385
Reputation: 991
You should rather do this. I did not get the time to test it but the SelectedValue should be string only so there should not be any need to do a ToString().
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string curItem = listBox1.SelectedValue.ToString();
MessageBox.Show(curItem);
}
To show everything I'd try this as pointed out in one of the comments too. You can grab the entire object, cast it to your class. Then you have access to all what's in the object. Hope this works!
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SectorBodies curItem = listBox1.SelectedItem as SectorBodies;
MessageBox.Show(curItem.StringPosition);
}
Upvotes: 1