我正在尝试从组合框中获取当前选择的选项,并且尝试通过它获取文本
ComboBox.Text
Combobox.SelectedItem()
但.Text
返回一个空字符串并SelectedItem()
返回 null
这是关于我如何填充组合框的代码。组合框的值取决于另一个组合框的值。
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;
}
虽然我可以看到.Text
组合框中的值,但我无法在代码中使用它们。
编辑:空值由cboPlan
组合框返回。
这是当它返回 null 的情况下SelectedItem()
和空字符串的情况下.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。
<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" />