我有一个组合框,通过Datasource(Datatable)加载 . 在一个场景中,我希望组合框加载所需的值,我将传递给combobox1.SelectedValue = custId(说它是客户详细信息) . custID在XAML中设置为SelectedValuePath . 当我设置它时,我得到一个null异常 . 我错过了什么?
我的XAML:
<ComboBox Height="23" HorizontalAlignment="Left" Margin="332,42,0,0" Name="cmbCustomerName" VerticalAlignment="Top" Width="240" IsEditable="True" DisplayMemberPath="customername" SelectedValuePath="custid" ItemsPanel="{StaticResource cust}" SelectionChanged="cmbCustomerName_SelectionChanged" AllowDrop="True" FontWeight="Normal" Text="--Select a Customer Name--" IsSynchronizedWithCurrentItem="True" />
UPDATE:
C#代码:
public customer(int custid)
{
InitializeComponent();
cmbcustomer.SelectedValue= custid.ToString();
}
private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
cmbcustid.SelectedValue= cmbcustomer.SelectedValue;
}
4 回答
selectedValue在这种情况下不起作用,您应该使用selectedItem,例如:
combobox1.SelectedItem =“custId”;
要么
combobox1.Text =“custId”;
要么
combobox1.SelectedIndex = combobox1.Items.IndexOf(“custId”);
要么
combobox1.SelectedIndex = combobox1.FindStringExact(“custId”)
我会建议你一个方法
作为临时解决方案,您可以尝试这一点
等待访问
ComboBox
es的任何属性,直到它们被加载为止:我通过在combox_loaded事件中分配值来解决问题,因为组合框刚刚在构造函数中初始化,但它没有从数据源加载 .