简体   繁体   中英

how to get value from dynamically added combobox in wpf c#?

I want get the data from combobox in WPF.

below is mu sample code.

<ComboBox Name="cmbCompanies" Height="110" Width="560" HorizontalAlignment="Right"  SelectionChanged="cmbCompanies_SelectionChanged">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Name}"/>
                            </StackPanel>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
            </ComboBox>

my code-behind is:

to bind the data to combobox:

 JArray companies = (JArray)response["data"];
            System.Diagnostics.Debug.WriteLine(companies.Count);
            if (companies.Count == 0)
            {
                // alert no compaies associated with this account.
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(companies);


                for (int i = 0; i < companies.Count; i++)
                {

                    Companies com = new Companies();
                    com.Id = (string)companies[i]["id"];
                    com.Name = (string)companies[i]["name"];

                    cmbCompanies.Items.Add(com);

                }

to get the data:

private void cmbCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //     string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
            string item = (sender as ComboBox).SelectedItem.ToString();


            string tmp = (cmbCompanies.SelectedValue as ComboBoxItem).Content.ToString();


        }

I am trying the above code but i am getting the any values, please help on this.

Do some reading about Data Binding in WPF. Create an object to be used as a ViewModel. Inside of the ViewModel add a property of a collection type (Observablecollection works). Bind the ItemsSource property of the ComboBox to your collection. Anything you add to your collection from now on will appear in your ComboBox

Cast the SelectedItem property to a Companies object:

private void cmbCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Companies selectedCompany = (sender as ComboBox).SelectedItem as Companies;
    if (selectedCompany != null)
    {
        string id = selectedCompany.Id;
        string name = selectedCompany.Name;
    }
}

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