Reputation: 8652
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"];
}
Upvotes: 0
Views: 4962
Reputation: 3808
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
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();
Upvotes: 2
Reputation: 13765
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
Upvotes: 1