문제

I am trying to transfer the selected items of one combo box to another using following code:

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

The ComboBoxItem class is user-defined and used to store combo box text and values together.

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;
       }
   }

But the code is throwing NullReferenceException and I am unable to find a reason for it. The values are being fetched like this from ComboBox: enter image description here But not assigning them to ComboBoxItem's object shift1Driver. Please help.

도움이 되었습니까?

해결책

As you indicated in the comments that the type of your SelectedItem is DataRowView you have no cast available. Instead build your type ComboBoxItem manually like so:

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

Or a little bit more condensed:

comboBoxAccountsDriverName.Items.Add(new ComboBoxItem {
     Text = ((DataRowView) comboBoxDriverShift1.SelectedItem)[1].ToString(),
     Value = ((DataRowView) comboBoxDriverShift1.SelectedItem)[0]
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top