user2762462
user2762462

Reputation: 11

How can I return multiple string values using while loop+

This is what I want: A method that is within a class that will return iteratively the values of a certain column. This values will the be added to a combobox when the method is invoked. Here is my attempt:

  public string FillCombo()
      {
            string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
            string query = "Select * from categorias";
            SqlConnection conn = new SqlConnection(connstring);
            SqlCommand command = new SqlCommand(query, conn);
            SqlDataReader read;
                conn.Open();
                read = command.ExecuteReader();
                while (read.Read())
                {
                    string combodata = read.GetString(1);
                    return (combodata); 
                }
               return null;
        }

however, when this method is invoked, it only returns the first row into de combobox, not the other values.

Upvotes: 1

Views: 1343

Answers (2)

gpmurthy
gpmurthy

Reputation: 2427

Consider using a List of string as an output. The following minor change to your code should help...

public List<string> FillCombo()
{
    List<string> comboList = new List<string>();
    string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
    string query = "Select * from categorias";
    SqlConnection conn = new SqlConnection(connstring);
    SqlCommand command = new SqlCommand(query, conn);
    SqlDataReader read;
    conn.Open();
    read = command.ExecuteReader();
    while (read.Read())
    {
        string combodata = read.GetString(1);
        comboList.Add(combodata);
    }
    return comboList;
}

Good Luck!

Upvotes: 0

Reactgular
Reactgular

Reputation: 54801

It's called yield

http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx

From the manual

public static System.Collections.IEnumerable Power(int number, int exponent)
{
    int result = 1;

    for (int i = 0; i < exponent; i++)
    {
        result = result * number;
        yield return result;
    }
}

yield will send a collection of return results from inside a loop after the loop has completed.

You can close data connections using a try/finally block around the loop.

  public IEnumerable FillCombo()
  {

        SqlConnection conn = new SqlConnection(connstring);
        SqlCommand command = new SqlCommand(query, conn);
        SqlDataReader read;
        conn.Open();
        read = command.ExecuteReader();
        try
        {
            while (read.Read())
            {
                yield return read.GetString(1);
            }
        }
        finally
        {
            read.close();
            conn.close();
        }
    }

A cool and often overlooked feature of C#

Upvotes: 1

Related Questions