0

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.

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107
  • 1
    Obviously, `SelectedItem` is not `ComboBoxItem`. I can see first letters of its type on the screenshot: `System.Dat...` – Dmitry Mar 21 '14 at 12:33
  • then how should I solve this? It's actually working in my another application with same logic. This logic I took from here: http://stackoverflow.com/questions/3063320/combobox-adding-text-and-value-to-an-item-no-binding-source – Aishwarya Shiva Mar 21 '14 at 12:35
  • Use the debugger to inspect what Type `comboBoxDriverShift.SelectedItem` is. – rene Mar 21 '14 at 12:38
  • As a guess, you combobox is data-binded. In this case, its items have type of the `DataSource`'s items. – Dmitry Mar 21 '14 at 12:41
  • @rene its `DataRowView` type. How should I type cast it? – Aishwarya Shiva Mar 21 '14 at 12:57

1 Answers1

1

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]
});
rene
  • 41,474
  • 78
  • 114
  • 152
  • Thanks, I modified my code according to your answer like this `ComboBoxItem shift1Driver = new ComboBoxItem() { Text = ((DataRowView)comboBoxDriverShift1.SelectedItem).Row.ItemArray[1].ToString(), Value = (((DataRowView)comboBoxDriverShift1.SelectedItem).Row.ItemArray[0]) };` and its working. – Aishwarya Shiva Mar 21 '14 at 13:30