gpt4 book ai didi

c# - 清除和重新填充绑定(bind)的组合框

转载 作者:太空狗 更新时间:2023-10-29 18:28:56 24 4
gpt4 key购买 nike

我有一个 WPF 应用程序,其中包含许多组合框。当我切换 comboboxx #1、combobox #2 等开关时

这是 2 个组合框的 xaml:

<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 在一开始就被填充,不需要重置。这里是调用部门变更的代码,应该会触发客户变更:

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);

}

当我进行索引更改时,它会调用一个调用以下代码的后台工作程序:

    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;


}

问题是我无法在 CboDivision 上切换选择并清除 CboCustomerList 并将新值重新加载到其中。这是我在 xaml 中绑定(bind)值的方式吗?如何更改 CboDivision 以清除 CboCustomerList 项目,然后执行填充例程?

我目前正在重置组合框:

CboCustomerList.SelectedIndex = -1;

但这只是将新的 cbocustomerlist 查询附加到末尾我也试过了

CboCustomerList.Items.Clear()

但是在框被重新填充并且用户选择了一个项目之后,它只会返回空引用错误。

最佳答案

好吧,您没有发布所有代码,但一个问题是您没有调用工作线程。

FillCustomers(null, null) 替换为 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
}

如果这有帮助,请告诉我。如果还有更多问题,请发布您的其余代码。

关于c# - 清除和重新填充绑定(bind)的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com