如何从wpf中的组合框中获取所选值?

时间:2015-04-29 16:30:00

标签: c# wpf entity-framework

我在组合框中选择项目后尝试获取DepartmentId,然后将其分配给nameTextBox.Text。但是当我运行程序时,它会给出Null Reference Exception。

{{1}}

2 个答案:

答案 0 :(得分:1)

在某个时刻,departmentCombobox.SelectedValuenullToString()上的null被调用。

您可以使用?运算符; 您还可以在尝试访问ComboBox之前选择其第一项:

var deptList = dr.ReadAllDepartment();            
departmentCombobox.DisplayMemberPath = "DepartmentName";
departmentCombobox.SelectedValuePath = "DepartmentId";
departmentCombobox.ItemsSource = deptList;

departmentCombobox.SelectedIndex = 0;
nameTextBox.Text = departmentCombobox.SelectedValue?.ToString();

答案 1 :(得分:0)

SelectedValue为null,因为没有选定的值。在设置ItemSource到尝试访问SelectedValue的短暂时间内,用户没有选择任何值。

相关问题