-1

I have 25 ComboBoxes that I want to move all of the values into an array so that i can put them into SQL Server. The current method that I am using is

string[] Answers = { cbxIntro.SelectedValue.ToString(), 
cbxAge.SelectedValue.ToString(), etc

This then throws up the error code

System.NullReferenceException: 'Object reference not set to an instance of 
an object.'

Any help would be greatly appreciated

zaggler
  • 7,254
  • 6
  • 26
  • 47
  • `cbxIntro.SelectedValue` || `cbxAge.SelectedValue` is likely `null` and by casting the `SelectedValue` to a `string` is the error because it's null. Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – zaggler Aug 19 '19 at 15:22
  • `SelectedValue` wont do anything with *all the values*. – Ňɏssa Pøngjǣrdenlarp Aug 19 '19 at 15:39

1 Answers1

-1

sounds like one of your values is null try adding Coalesce and ifNotNull operators

ie

string[] Answers = { cbxIntro?.SelectedValue?.ToString() ?? "default", cbxAge?.SelectedValue?.ToString() ?? "default", ...

which reads as if cbxIntro is not null call SelectedValue if SelectedValue is not null call Tostring else return "default" string

MikeT
  • 4,398
  • 2
  • 23
  • 34