I am trying to get currently selected option from a combobox and I’ve tried getting it’s text through
ComboBox.Text
Combobox.SelectedItem()
but .Text is returning an empty string and SelectedItem() is returning null
Here is the code on how I am populating the combobox. The combobox value depends on the value of another combobox.
private void cboSite_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
cboPlan.Items.Clear();
bw.DoWork += new DoWorkEventHandler(bw_cboPlan);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_cboPlanComplete);
site = cboSite.SelectedItem.ToString();
Busy.IsBusy = true;
Busy.BusyContent = "Loading Products";
bw.RunWorkerAsync();
}
void bw_cboPlan(object sender, DoWorkEventArgs e)
{
SqlConnection con = new SqlConnection(Class.GetConnectionString());
SqlCommand scProduct = new SqlCommand("spSelectProduct", con);
scProduct.Parameters.Add(new SqlParameter("@Site",site));
scProduct.CommandType = CommandType.StoredProcedure;
SqlDataReader readerPortal;
con.Open();
readerPortal = scProduct.ExecuteReader();
while (readerPortal.Read())
{
this.Dispatcher.Invoke((Action)delegate(){cboPlan.Items.Add(readerPortal[0]);});
}
con.Close();
}
void bw_cboPlanComplete(object sender, RunWorkerCompletedEventArgs e)
{
cboPlan.SelectedIndex = 0;
Busy.IsBusy = false;
}
Though I can see the .Text values in the combobox I cannot use them in code.
EDIT: The Null values is returned by the cboPlan Combobox.
And here is when it returns the null in case of SelectedItem() and empty string in case of .Text
if (IsValid())
{
BackgroundWorker bw = new BackgroundWorker();
cboPlan.Items.Clear();
bw.DoWork += new DoWorkEventHandler(bw_Add);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_AddComplete);
plan = cboPlan.Text;
Busy.IsBusy = true;
Busy.BusyContent = "Sending Request.";
bw.RunWorkerAsync();
}
XAML for The Comboboxes.
<ComboBox x:Name="cboSite" HorizontalAlignment="Left" Margin="461,52,0,0" VerticalAlignment="Top" Width="174" SelectionChanged="cboSite_SelectionChanged"/>
<ComboBox x:Name="cboPlan" HorizontalAlignment="Left" Margin="395,106,0,0" VerticalAlignment="Top" Width="240" />
Edit
Well, you have this in your code:
I am not sure what are you trying to do, but if you want to save value of the control, do that before calling
Items.Clear()function.Original answer
I suggest that you fill List from database in
bw_cboPlan, and to fill ComboBox inRunWorkerCompletedEventHandlercallback function: