Click here to Skip to main content
15,890,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am trying to return array of class type from asmx service but i am getting Object reference not set to an instance of an object. error here is my code please do let me know how to solve this problem.
C#
LabsResponse labresponse = new LabsResponse();
           Lab[] labs = new Lab[1];

           string cs = ConfigurationManager.ConnectionStrings["DatabaseContext"].ConnectionString;

           using (SqlConnection con = new SqlConnection(cs))
           {
               int i = 0;
               SqlCommand cmd = new SqlCommand("Select * from Labs where clinicNumber=" + clinicNumber, con);

               con.Open();
               SqlDataReader reader = cmd.ExecuteReader();

               while (reader.Read())
               {

                  labs[i].CategoryName =reader[0].ToString();
                 labresponse.Labs = labs;
                 i++;

               }
               con.Close();

               return labresponse;


labresponse class

C#
  public partial class LabsResponse : ServiceResponse
    {

        private Lab[] labsField;

        /// <remarks />
        [System.Xml.Serialization.XmlArrayAttribute(IsNullable = true)]
        [System.Xml.Serialization.XmlArrayItemAttribute(Namespace = "http://schemas.datacontract.org/2004/07/Mayo.Cdans.Labs.Objects")]
        public Lab[] Labs
        {
            get
            {
                return this.labsField;
            }
            set
            {
                this.labsField = value;
            }
        }
    }

when i a trying to assign value to labs[i].CategoryName it gives above mentioned error what can be done please help. thanks in advance.
Posted
Updated 3-Jan-16 22:32pm
v2
Comments
U. G. Leander 4-Jan-16 4:46am    
check the value of "i" when the error occurs (-> set breakpoint there). I am sure that "i" is greater than "0". But "labs" has only a length of one, i.e. one element....so when you try to write to e.g. "labs[1]", this object is not instantiated (it is not even existing).

C#
labs[i].CategoryName =reader[0].ToString();

Make sure labs array and reader[0] are not null.
This error occurs when a member of a null object is accessed.
 
Share this answer
 
C#
labs[i].CategoryName =reader[0].ToString();

this line can be written like

C#
labs[i].CategoryName =Convert.ToString(reader[0]);

This will not throw an error in case of null value in db.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900