C# 如何从wpf中的组合框中获取所选值?
在组合框中选择项目后,我试图获取部门ID,然后将其分配给nameTextBox.Text。但当我运行程序时,它会给出Null引用异常C# 如何从wpf中的组合框中获取所选值?,c#,wpf,entity-framework,C#,Wpf,Entity Framework,在组合框中选择项目后,我试图获取部门ID,然后将其分配给nameTextBox.Text。但当我运行程序时,它会给出Null引用异常 var deptList = dr.ReadAllDepartment(); departmentCombobox.DisplayMemberPath = "DepartmentName"; departmentCombobox.SelectedValuePath = "DepartmentI
var deptList = dr.ReadAllDepartment();
departmentCombobox.DisplayMemberPath = "DepartmentName";
departmentCombobox.SelectedValuePath = "DepartmentId";
departmentCombobox.ItemsSource = deptList;
nameTextBox.Text = departmentCombobox.SelectedValue.ToString();
SelectedValue为空,因为没有选定的值。在您设置ItemSource和尝试访问SelectedValue之间的短暂时间内,用户没有选择值。在某个时间点
departmentCombobox。SelectedValue
为null
,并且正在null
上调用ToString()
您可以使用?
操作符;
在尝试访问组合框之前,您还可以选择组合框上的第一项:
var deptList = dr.ReadAllDepartment();
departmentCombobox.DisplayMemberPath = "DepartmentName";
departmentCombobox.SelectedValuePath = "DepartmentId";
departmentCombobox.ItemsSource = deptList;
departmentCombobox.SelectedIndex = 0;
nameTextBox.Text = departmentCombobox.SelectedValue?.ToString();
您可以使用SetValues。