Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从wpf中的组合框中获取所选值?_C#_Wpf_Entity Framework - Fatal编程技术网

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

C# 如何从wpf中的组合框中获取所选值?,c#,wpf,entity-framework,C#,Wpf,Entity Framework,在组合框中选择项目后,我试图获取部门ID,然后将其分配给nameTextBox.Text。但当我运行程序时,它会给出Null引用异常 var deptList = dr.ReadAllDepartment(); departmentCombobox.DisplayMemberPath = "DepartmentName"; departmentCombobox.SelectedValuePath = "DepartmentI

在组合框中选择项目后,我试图获取部门ID,然后将其分配给nameTextBox.Text。但当我运行程序时,它会给出Null引用异常

        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。