Question

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.

Was it helpful?

Solution

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]
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top