2

I have a combo box that I want to load with a string array that is returned from a method. I currently just have this being loaded with a for loop but I think there should be away to just assingn the string array directly to the combo box. (I'm just trying to improve my code)

I've done some searching and I've seen answers using datarange or datasource but neither of these seem to work. I also have tried datacontext as that seemed like a possibility. Is there something I'm missing or there not a way to assing the array all in one line?

I am using C# WPF and the file is the MainWindow.xaml.cs

Thanks!

0

3 Answers 3

4

Try this:

cbxList.ItemsSource = new string[] { "hello", "from", "mars" };
Sign up to request clarification or add additional context in comments.

Comments

3

ItemsSource is what you want to assign to.

(DataSource is used in Windows Forms, you normally will not encounter it in WPF. If you want to understand DataContexts you need to read up on data binding which is very useful.)

4 Comments

@H.B.-is there a way to implement this without the need to change the xaml code and just do it in the c# (xaml.cs)?
You can set the ItemsSource from there. But like H.B. said, you should really research MVVM and data binding if you will do a lot of WPF. With MVVM, you will have a viewmodel, which is sort of a UI-less representation of what you want to display. So in your case, you want to display a combobox with some text items; in your viewmodel that would be represented by a collection of strings. When you add or remove strings from that collection, they would appear in your UI via the binding.
@Johnston: If you named the ComboBox e.g. cb you can just assign to it using cb.ItemsSource = ...
@H.B: That was it Thanks! I was trying to do cb.ItemsSource(stringArray) and other variations with cb.ItemsSource.equals(stringarray) Thanks for the help!!
0

Function to fill a comboBox:

public void FillComboBox(string[] array, ComboBox box)
{
 foreach(string x in array)
  {
   box.Items.Add(x);
  }
}

How to use: (Example)

private void Button1_Click(object sender, EventArgs e)
{
 string[] fruits = {"banana","apple","orange"};
 FillComboBox(fruits,comboBox1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.