【问题标题】:How to get the selected value from combo box in wpf?如何从 wpf 的组合框中获取选定的值?
【发布时间】:2015-04-29 16:30:00
【问题描述】:

我试图在选择组合框中的项目后获取 DepartmentId,然后将其分配给 nameTextBox.Text。但是当我运行程序时,它给出了空引用异常。

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

【问题讨论】:

标签: c# wpf entity-framework


【解决方案1】:

SelectedValue 为空,因为没有选定的值。在您设置 ItemSource 和尝试访问 SelectedValue 之间的短暂时间内,用户没有选择值。

【讨论】:

    【解决方案2】:

    在某些时候departmentCombobox.SelectedValuenull 并且ToString() 正在被null 调用。

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

    var deptList = dr.ReadAllDepartment();            
    departmentCombobox.DisplayMemberPath = "DepartmentName";
    departmentCombobox.SelectedValuePath = "DepartmentId";
    departmentCombobox.ItemsSource = deptList;
    
    departmentCombobox.SelectedIndex = 0;
    nameTextBox.Text = departmentCombobox.SelectedValue?.ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-27
      • 2018-02-05
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多