将所选项目从一个ComboBox传输到另一个ComboBox时出现NullReferenceException

时间:2014-03-21 12:26:39

标签: c# .net winforms combobox nullreferenceexception

我正在尝试使用以下代码将一个组合框的选定项目传输到另一个组合框:

ComboBoxItem shift1Driver = new ComboBoxItem(); 
shift1Driver.Text = (comboBoxDriverShift1.SelectedItem as ComboBoxItem).Text;
shift1Driver.Value = (comboBoxDriverShift1.SelectedItem as ComboBoxItem).Value.ToString();
comboBoxAccountsDriverName.Items.Add(shift1Driver);

ComboBoxItem类是用户定义的,用于将组合框文本和值存储在一起。

public class ComboBoxItem
   {
       public ComboBoxItem()
       {
           Text = "ComboBoxItem1";
           Value = "ComboBoxItem1";
       }
       public string Text { get; set; }
       public object Value { get; set; }

       public override string ToString()
       {
           return Text;
       }
   }

但代码正在抛出NullReferenceException,我无法找到原因。这些值是从ComboBox中获取的: enter image description here 但不将它们分配给ComboBoxItem的对象shift1Driver。请帮忙。

1 个答案:

答案 0 :(得分:1)

正如您在评论中指出的,您的SelectedItem的类型是DataRowView,您没有可用的演员表。而是手动构建类型ComboBoxItem,如下所示:

var rowView = (DataRowView) comboBoxDriverShift1.SelectedItem;  // cast 
ComboBoxItem shift1Driver = new ComboBoxItem {
     Text = rowView[1].ToString(),
     Value = rowView[0]
};
comboBoxAccountsDriverName.Items.Add(shift1Driver);

或者更浓缩一点:

comboBoxAccountsDriverName.Items.Add(new ComboBoxItem {
     Text = ((DataRowView) comboBoxDriverShift1.SelectedItem)[1].ToString(),
     Value = ((DataRowView) comboBoxDriverShift1.SelectedItem)[0]
});