tags:

views:

142

answers:

2

i have 5 names in a table and i need to put these in an arraylist....

any suggestions???

            int rowsinmachgrp = getnumofrows();//gets no of rows in table

            SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
            SqlCommand dataCommand =
                    new SqlCommand("select MachineGroupName from MachineGroups", dataConnection);

            {ArrayList names = new ArrayList();
                dataConnection.Open();
                ArrayList names = dataCommand.ExecuteScalar();

Thanks

A: 

Corrected Code:

ArrayList names = new ArrayList();

int rowsinmachgrp = getnumofrows();//gets no of rows in table

SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
SqlCommand dataCommand = new SqlCommand("select MachineGroupName from MachineGroups", dataConnection);


  dataConnection.Open();
  SqlDataReader rdr = dataCommand.ExecuteReader();
  while (rdr.Read())
  {
    names.Add(rdr.GetString(0));
  }
dataCommand.Dispose();
dataConnection.Dispose();

Please note that while I'm solving your direct problem, you've got a lot of other issues going on, such as your rowsinmachgrp variable, using an ArrayList, and not using using :)

JustLoren
+5  A: 

This is yours:

List<string> names = new List<string>();
using(SqlConnection db = new SqlConnection(ConfigurationManager...))
{
    db.Open();
    SqlCommand cmd = new SqlCommand("Select ....", db);

    using(SqlDataReader rd = cmd.ExecuteReader())
    {
        while(rd.Read())
        {
           names.Add(rd.GetString(0));
        }
    }
}

Not Tested!

Arthur
You are missing a closing parenthesis on the line where the name is being added to the list.
Eclipsed4utoo
THX! fixed it. And I don't know what to say to get 15 characters for this comment
Arthur
SQLdataread could not be found... error.. what is the usingcommand for dataread..??
The using defines the scope for the SqlDataRead, once it exits this it will be disposed. See http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx for more details
James
thanks...all...:)
Sorry, next Typo. I thought, I could write this blindly due to the fact that I'm writing this code snipped more than once a week.
Arthur