简体   繁体   中英

How to get a Combo box to output into text boxes after item selection

What I'd like to do is once the user has selected an item from the combo box, for it to then populate the text boxes with the corresponding data.

The error's I'm getting are:

The best overloaded method match for 'System.Collections.Generic.List.this[int]' has some invalid arguments

and

Argument '1': cannot convert from 'object' to 'int'

Here is a section of my code:

List<Venue> Ven = new List<Venue>();

    private void cboVenue_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            txtVenue.Text = Ven[cboVenue.SelectedItem].m_VenName;

        }
        catch
        {
        }
    }

Please, any help would really be appreciated. Thanks

If you are using databinding (or even if you are populating the combobox manually), just use databinding anyways...

<ComboBox x:Name="cmbBox" ItemsSource="{Binding Path=Ven}" />
<TextBox Text="{Binding Path=SelectedValue, ElementName=cmbBox}" />

Note that you want to grab the SelectedValue, not the SelectedIndex or SelectedItem. Though, depending on how you setup your combobox the SelectedItem might be equivalent to the SelectedValue... still, use SelectedValue.

Try this:

    txtVenue.Text = Ven[cboVenue.SelectedIndex].m_VenName;

You also have to check that the Index is >= 0, an Index of -1 is for "nothing selected"

try to replace:

txtVenue.Text = Ven[cboVenue.SelectedItem].m_VenName;

with:

txtVenue.Text = Ven[cboVenue.SelectedIndex].m_VenName;

A combobox's SelectedItem property is an object not an int . So when you try to access an item in your list you're getting the error.

If you have bound the data to the combobox such that SelectedItem does contain the list index value (but just as an object) all you need to do is cast it to an int and then use it to find the value in your list.

Eg

int index = Convert.ToInt32(cboVenue.SelectedItem)  

Then Ven[index] will contain what you need.

Alternatively you may need to look at the SelectedText, SelectedValue or Selectedindex properties of the combobox to work back to the value you require.

Try SelectedIndex instead of SelectedItem. it's integer.

List<Venue> Ven = new List<Venue>();

private void cboVenue_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        txtVenue.Text = Ven[cboVenue.SelectedIndex].m_VenName;
    }
    catch
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM