Search code examples
c#asp.netreturnexecutereader

ExecuteReader is returning only 1 value


I am using an ExecuteReader to return the values of QuestionText when QuestionnaireID matches my query. (See Database Design)

However my problem is that when I run the project my ExecuteReader only returns the last value that was input. For example, if I was to create 3 questions (A,B,C) under the questionnaireID of 1. The ExecuteReader would return Question C only.

How can I return all values in the QuestionText collumn that have the same questionnaireID?

Database Design

enter image description here

****.cs**

public string GetQuestionName(int QuestionnaireID)
        {
            string returnvalue = string.Empty;
            SqlCommand myCommand = new SqlCommand("GetQuestion", _productConn);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters.Add(new SqlParameter("@QUEST_ID", SqlDbType.Int));
            myCommand.Parameters[0].Value = QuestionnaireID;   
            _productConn.Open();
            SqlDataReader test = myCommand.ExecuteReader();
            while (test.Read())
            { 
               returnvalue = test.GetString(0);  
            }
            _productConn.Close();
            return returnvalue;        

        }

Stored Procedure

   USE [devworks_oscar]
    GO
    /****** Object:  StoredProcedure [hbo].[GetQuestion]    Script Date: 11/12/2011 13:12:36 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [hgomez].[GetQuestion]  
        (
        @QUEST_ID int
        )   
    AS
        /*SET NOCOUNT ON;*/
        SELECT QuestionText FROM [Questions] WHERE QuestionnaireID = @QUEST_ID
        RETURN

Thanks in advance.


Solution

  • Your reader is returning all the values but the code -

    returnvalue = test.GetString(0);
    

    will keep overwriting the returnvalue variable with the next value returned from the datareader so you will only be left with the last value.

    You could create a list of strings -

    List<string> list = new List<string>();
    

    then add each value returned to the list -

     while (test.Read())
     { 
         list.Add(test.GetString(0));  
     }
    

    then return the list from your function instead of a string.