2

I am doing an sql select statement on my web service in Visual Studio 2010. It is only from a column but there are multiple rows of data. How do I populate an arraylist with the data and return it?

[WebMethod]
        public List<String> getAccType(string bankId)
        {

            myConnection.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("SELECT TypeName FROM AccType where BankID = '" + bankId + "'", myConnection);
            myReader = myCommand.ExecuteReader();
            List<String> AccType = new List<string>();
            while (myReader.Read())
            {
                string iAccType = myReader["TypeName"].ToString();
                AccType.Add(iAccType);

            }
            return AccType;

        }
    }
3
  • How do you fetch the data, using what? Pure ado.net or some orm perhaps? Here's how you work with an ArrayList: msdn.microsoft.com/en-us/library/… Commented Jan 30, 2014 at 2:07
  • Return the array list from where? Commented Jan 30, 2014 at 2:43
  • I would avoid using an ArrayList and, instead, use a strongly-typed List<T> containing the data. Especially since all the data is coming from the same column this should be preferred. Commented Jan 30, 2014 at 2:48

1 Answer 1

1

While you could return an ArrayList, it would be better to return a strongly-typed collection, either a List<T> or IEnumerable<T> with an underlying List<T> collection, perhaps.

Here is an example using a SqlDataReader to extract data from a column and populate such a list. Note: I haven't included any error handling.

public IEnumerable<int> GetOrderIds()
{
    var ids = new List<int>();
    var queryString = "SELECT OrderID FROM dbo.Orders;";

    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(queryString, connection))
    {
        connection.Open();

        using (var reader = command.ExecuteReader())
        {
             while (reader.Read())
             {
                var id = reader.GetInt32(0);
                ids.Add(id);
             }
        }
    }

    return ids;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.