smark91
smark91

Reputation: 625

Retrieving value from Listbox Item

I have a problem getting back a values of a Listbox item. The listbox is populated with a custom class element that i made.

private void btnSave1_Click(object sender, EventArgs e)
    {
        ListItem li = new ListItem(
            int.Parse(txtId1.Text),
            txtName1.Text,
            int.Parse(txtMinLevel1.Text),
            int.Parse(txtMinAttr11.Text),
            int.Parse(txtMinAttr21.Text),
            float.Parse(txtDamage1.Text),
            float.Parse(txtAdditionalDmg1.Text),
            cmbAdditionalDmgType1.SelectedItem.ToString(),
            float.Parse(txtRange1.Text),
            float.Parse(txtCost1.Text)
            );
        list1.Add(li);

        lstWeapons1.DataSource = null;
        lstWeapons1.DataSource = list1;
        lstWeapons1.DisplayMember = "name";
        lstWeapons1.ValueMember = "id";
    }

    private void lstWeapons1_SelectedIndexChange(object sender, EventArgs e)
    {
        var text = lstWeapons1.SelectedItem.ToString();
    }

After the event text value is ListItem not the value I expect

Upvotes: 0

Views: 42

Answers (1)

Steve
Steve

Reputation: 216243

In your case every element of the Listbox is an instance of your custom class ListItem. Calling ToString() on this custom class is useless if you don't have defined an override of the ToString() method in your custom class. So you have these choices

private void lstWeapons1_SelectedIndexChange(object sender, EventArgs e)
{
    if(lstWeapons1.SelectedValue != null) 
       var text = lstWeapons1.SelectedValue.ToString();
}

or

private void lstWeapons1_SelectedIndexChange(object sender, EventArgs e)
{
    if(lstWeapons1.SelectedItem != null) 
    {
       ListItem item = lstWeapons1.SelectedItem as ListItem;
       var text = item.id.ToString();
    }
}

or

public class ListItem
{
    public override string ToString()
    {
        return this.id.ToString();
    }
}

private void lstWeapons1_SelectedIndexChange(object sender, EventArgs e)
{
    if(lstWeapons1.SelectedItem != null) 
    {
       var text = lstWeapons1.SelectedItem.ToString();
    }
}

Notice that I always check if the SelectedItem or SelectedValue are null because you can't rule out the possibility that SelectedIndexChanged will be called when there is no item selected

Upvotes: 1

Related Questions