0

I have a company table and i used query select * from company .But now i only require all the company name from this table , how toget and store in to a string array.Following code snippet only one i raw of company name i get. but how to get all company names and store in to an array

reader = cmd.ExecuteReader();

            // write each record
            while(reader.Read())
            {
                Console.WriteLine("{0}", 
                    reader["CompanyName"]; 

            }
peter
  • 8,158
  • 21
  • 66
  • 119

2 Answers2

2

Option 1: Using an ArrayList

ArrayList dynamically resizes. As elements are added,and space is needed, it grows in capacity. It is most often used in older C# programs.

ArrayList companylist = new ArrayList();

reader = cmd.ExecuteReader();

// write each record
while(reader.Read())
 {
    companylist.Add(reader["CompanyName"]);
 }

foreach (var name in companylist)
{ 
   Console.WriteLine(name);
}

Option 2: Using a List

Replacement for deprecated ArrayList.

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

reader = cmd.ExecuteReader();

// write each record
while(reader.Read())
 {
    companylist.Add(reader["CompanyName"]);
 }

foreach (var name in companylist)
{ 
   Console.WriteLine(name);
}

//Converting list to string Array
var CompanyNamesArray = companylist.ToArray();
Community
  • 1
  • 1
WorkSmarter
  • 3,738
  • 3
  • 29
  • 34
1

Not sure if you need it in an array specifically, or just a collection... but you could do the following:

reader = cmd.ExecuteReader();

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

        // write each record
        while(reader.Read())
        {
            Console.WriteLine("{0}", 
                reader["CompanyName"]; 
            listOfCompanyNames.Add(reader["CompanyName"]);
        }

        var arrayOfCompanyNames = listOfCompanyNames.ToArray();

Note you'll need to import System.Collections.Generic and System.Linq

Kritner
  • 13,557
  • 10
  • 46
  • 72