could not add data to the ComboBox from parametarised constructor

catalina beaver 41 Reputation points
2022-06-07T12:42:11.237+00:00

I'm trying to populate ComboBox. I'm able to add items from the default consctructor but not from the parameterised constructor.

 public  Dashboard()
        {
            this.InitializeComponent();
            MyCombobox1.Items.Add("item_constructor 1"); // this item is added successfully
        }

 public Dashboard(int count, string[] arr)
        {
            this.InitializeComponent();         
            local_arr = arr;
             for (int i = 0;i<count;i++)
             {
                 MyCombobox1.Items.Add(local_arr[i]); // not added..no error thrown                          
             }        
        }

 private async void button_Click(object sender, RoutedEventArgs e)
        {
          MyCombobox1.Items.Add("item_button_click"); // item added successfully
        }

The XAML code for the ComboBox..

<ComboBox
                Name="MyCombobox1"
                x:FieldModifier="public"
                Grid.Row="0"
                Grid.Column="1"
                Canvas.Left="-121"
                Canvas.Top="150"
                Margin="450,360,0,0"
                Background="#F1F1F5"
                FontSize="24"

                Header=" Choose file"
                PlaceholderText="select"
                RenderTransformOrigin="0.575,1.825"
                SelectionChanged="MyCombobox1_SelectionChanged"
                 >

            </ComboBox>

I'm not able to understand the mistake. Thank you.

Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,292 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,540 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2022-06-07T13:38:34.523+00:00

    Alternate, set the ItemSource

    ExampleComboBox.ItemsSource = new List<string>() { "First", "Second" };
    ExampleComboBox.SelectedIndex = 0;
    

    Add item later

    var list = (List<string>)ExampleComboBox.ItemsSource;
    list.Add("Last");
    ExampleComboBox.SelectedIndex = list.Count - 1;
    
    1 person found this answer helpful.