Clearing and refilling a bound combo box

I have a WPF application with a number of comboboxes that tie together. When I switch comboboxx #1, combobox #2 switches, etc.

Here is the xaml for the 2 comboboxes:

<ComboBox Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,12,286,0" ItemsSource="{Binding}" Name="CboDivision" VerticalAlignment="Top" Width="120" SelectionChanged="CboDivision_SelectionChanged" /> <ComboBox Height="23" HorizontalAlignment="Right" Margin="0,9,32,0" Name="CboCustomerList" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" SelectionChanged="CboCustomerList_SelectionChanged" Grid.Row="1" />

CboDivision gets populated at the beginning and doesnt need a reset. HEre is the code that calls the change in division, which should trigger a change in customer:

private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e) { division = CboDivision.SelectedValue.ToString(); CboCustomerList.ItemsSource = null; BackgroundWorker customerWorker = new BackgroundWorker(); customerWorker.DoWork += new DoWorkEventHandler(FillCustomers); customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted); FillCustomers(null, null); }

When I do an index change it calls a backgroundworker which calls the following code:

private void FillCustomers(object sender, DoWorkEventArgs e) { string connectionString = Settings.Default.ProdConnectionString; SqlConnection connection = new SqlConnection(connectionString); SqlCommand SqlCmd = new SqlCommand(); Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; SqlCmd.CommandType = CommandType.StoredProcedure; SqlCmd.Parameters.Add("@division", SqlDbType.NVarChar).Value = division; SqlCmd.Connection = connection; SqlCmd.CommandText = "sp_GetCustomers"; SqlDataReader reader = null; connection.Open(); reader = SqlCmd.ExecuteReader(); List<string> result = new List<string>(); while (reader.Read()) { result.Add(reader["NAME"].ToString()); } e.Result = result; }

The problem is that i am unable to switch selections on CboDivision and have CboCustomerList clear and reload new values into it. Is it the way I'm binding the values in the xaml? How can I have a change in CboDivision cause a clearing of CboCustomerList items, then the execution of the filling routine?

i am currently resetting the combobox with:

CboCustomerList.SelectedIndex = -1;

but this just appends the new cbocustomerlist query to the end I also tried


but that just returns a null reference error after the box is refilled and the user selects an item.

-------------Problems Reply------------

Well, you didn't post all of your code, but one problem is that you are not invoking your worker thread.

Replace FillCustomers(null, null) with customerWorker.RunWorkerAsync().

private void CboDivision_SelectionChanged(object sender, SelectionChangedEventArgs e)
division = CboDivision.SelectedValue.ToString();
CboCustomerList.ItemsSource = null;

BackgroundWorker customerWorker = new BackgroundWorker();
customerWorker.DoWork += new DoWorkEventHandler(FillCustomers);
customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(customerWorker_RunWorkerCompleted);
customerWorker.RunWorkerAsync(); // <-- this

Let me know if this helps. If there is still more problem, please post the rest of your code.

There are details of code you didn't show. However, here is an example that works: two combos, what that is populated at the beginning, and a second that is populated each time the selection changes in the first. Notice that the data is fetched in a background worker, just as in your case.


<Window x:Class="CombosRefresh.MainWindow"
Title="MainWindow" Height="350" Width="525">
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />

<ComboBox Name="CboDivisions" ItemsSource="{Binding}" Grid.Row="0" Margin="5" />
<ComboBox Name="CboList" ItemsSource="{Binding}" Grid.Row="1" Margin="5" />


public partial class MainWindow : Window
private BackgroundWorker bw = new BackgroundWorker();

public MainWindow()

CboDivisions.DataContext = new List<string>() { "red", "blue", "green" };
CboDivisions.SelectionChanged += CboDivisions_SelectionChanged;

bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;

void CboDivisions_SelectionChanged(object sender, SelectionChangedEventArgs e)
var division = CboDivisions.SelectedValue as string;

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
CboList.DataContext = e.Result as List<string>;

void bw_DoWork(object sender, DoWorkEventArgs e)
var division = e.Argument as string;

var r = new Random();
var result = new List<string>();

for(int i = 0; i < r.Next(0, 10); ++i)
result.Add(string.Format("{0} #{1}", division, i+1));

e.Result = result;

replace the wrong FillCustomers(null, null); code with: customerWorker.RunWorkerAsync();

Category:c# Views:5 Time:2018-05-05
Tags: wpf xaml combobox

Related post

  • What is the best way to sort a data bound combo box? 2008-08-27

    I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). If that is the case then the question becomes what is the best way to sor

  • Need sample JavaScript to query MySQL and display result upon combo box update 2009-08-19

    I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that th

  • When I save a file and reopen it, the combo boxes have moved. 2015-01-06

    I'm using office 08 on an iMac. I built a spreadsheet and I'm using combo boxes to display items in a drop down list. When I save the file and open it back up the combo boxes move from their original location. This continues to happen over and over a

  • Disable separator selection in data bound combo box in WPF 2010-11-23

    I have a Combo Box that is databound. In this list, I need a separator. Since this is databound, I do something very similar to this post. My database returns the list, includes a '-' to mark where the separator needs to go, and the datatrigger makes

  • Changing background color of a separator in WPF data bound combo box 2010-11-24

    I have a combobox that is bound to a dataset that then uses a datatrigger to insert a separator when it encounters a '-' in the data (example in this question). The background of the menu has custom color, set by using a resource dictionary. The colo

  • Bound combo box not pulling correct values 2012-10-19

    i have a combo box in an ADP file connected to SQL server. the combo box is within a subform and has the following properties: rowsource: Select ID, strdescrption, strStoreAccount FROM tblNewAccountDescription WHERE Active = 1 ORDER BY ID bound colum

  • Bound Combo Boxes on Forms 2013-05-11

    Hi, I have created a form that has two controls, one labeled “Date of Deal,” and the other labeled, “Supplier.” For now, the controls are text boxes. The form accepts these two inputs and then outputs a report titled, “Analysis of Specific Deals.” Th

  • Make table query and preserve value in combo box derived from lookup table. 2014-08-28

    Hello, I have table called Ground data that contains a combo box called Species that looks up a value from a lookup table. The lookup query is this: SELECT GroundVegList.GroundVegListID, GroundVegList.[7 Letter Code], GroundVegList.[Scientific Name],

  • changing cornerradius of Flex label and changing arrow of combo box 2009-08-14

    I have two questions. How do I change the corner radius of a Label component in Flex. Tried applying style name, and the setStyle('cornerRadius',9) methods, but doesn't work. How can I change the arrow image in the combo box control to a different im

  • How to make a data-bound combo box display (like a DisplayMember) a concatenated string? 2010-05-08

    I have a first name and a surname as separate columns in a table. If I bind a combo box to a query and set DisplayMember property to "Name" then each person a table is represented in a combo box by its name. How do I show each person's full name (bui

  • retrieve mysql data as array and display in multiple combo boxes 2011-06-02

    i am trying to use the mysql data items into the select combo box. it basically works well but the problem is when there are multiple combo boxes it is a lot of load to the server since adding each combo box takes a lot of time. i am trying to figure

  • how to read XML using XLinq and bind it to Combo Box? 2011-06-09

    Hi I am trying to read XML File using XLinq and binding the values into Combo Box:- XDocument xmlDoc = XDocument.Load("abc.xml"); var res = from c in xmlDoc.Element("Clients").Descendants("Client") select c; cmb1.BindingContext = new BindingContext()

  • Converting text boxes to combo boxes and adding values to combo box using vba 2012-11-21

    Hello, Depending on user selections a set of questions will populate on the form Some of the questions require responses from a drop down box Depend to the question_ ids I want to convert text box to combo box and get the values for the combo box fro

  • creating an invoice number from date and values in other combo boxes 2013-10-11

    I am sure I have the syntax wrong - see below Me.InvoiceNumber = Me.cboAgnCat & "-" & "#format(now(),"yyymmdd")#" I am attaching this to a command button to create invoice number - want it to show category todays date and a sequence number st

  • java swing combo box selection and link to other combo boxes 2011-09-08

    Here is the scenario: I have a table in database with 3 columns (id, name, age). I've created 3 swing comboboxes and a button that sends a "select statement" to the database and fills the comboboxes out with addItem(...). Now i wanna know how to link

  • How to select between Call and Execution using a Combo Box in AspectJ 2012-03-29

    i am currently implementing a logger using aspectj. Now i want to have a GUI from where i can select which one to choose i.e Call or Execution. Based on the selection the AOP will work and log the information. Is it possible to achieve this? Can anyo

  • Access 2010 bug - filter by form won't clear default value in combo box 2013-05-25

    First of all let me say as a representative of the user community - and a long-time user of Access - Microsoft should be taking the leadership position and setting a worldwide standard for making it easy for users to report bugs. Currently it's entir

  • How do stop a combo box from clearing after I move to the next record? 2013-06-18

    I have a submit button and it clears all data after clicking it and I need the combo box not to clear when I select the button. I have another button to clear all the data. I am using Access 2010. --------------Solutions------------- Hmm, This would

  • How to clear the selection on combo box 2014-04-07

    Hi i have a form to enter the criteria for a report query. at first run it gives the exact result. after i close the report and returned back to the form when i selecting a new item to run the report for second time it remembers the old selection and

  • Updating and Syncing Combo Box 2012-05-18

    Hello, I could use some help...I have a form that has several subforms on it (on tabs). I have a combo box on the main form that is syncing with a combo box on the subform tab. Everything is syncing fine as far as navigating from established records,

  • Enter Combo Box value by the 2nd column not the bound column 2012-02-02

    Normally, in vba, I could assign a combo box's value by doing something like Me.Combobox1 = 3 In the context of a combo box with 2 columns (PK & Textual Description) where col 0 is hidden and we display col 1 how can I pass the value of col 1 to

  • Combo box and text box update 2012-04-13

    I have a bound combo box on a "single" form. The combo box is bound to a table contained an ID, school name, and SAU number. When the user chooses a school name, I would like the text box to display the SAU. Can someone point me in the right directio

  • have option button and combo box go together 2012-09-06

    I created some option button in a frame. Beside each button, there are one or more corresponding combo boxes. I want that the option button and its corresponding combo box are always correlated with each other. Also, only one option button within a f

  • Access 2007 problem: Combo box stores the source ID and not the value into the table 2014-03-02

    I have two combo boxes, Topic and Subtopic, and I use the following code to set the rowsource for the Subtopic based on the Topic that is selected: Private Sub Topic_AfterUpdate() Me.Subtopic.RowSource = "SELECT [Topics].[Subtopic], [Topics].[Topic],

Copyright (C), All Rights Reserved.

processed in 0.089 (s). 11 q(s)