Search code examples
c#sqlreturnselectall

get all row and column data using SELECT - C#


I'm trying to get all data from an SQL table and store it in a List using the C# programming language.

the SQL statement I'm using is:

private string cmdShowEmployees = "SELECT * FROM Employees;";

This is being used in the same class as a function

public List<string> showAllIdData()
{
  List<string> id = new List<string>();
  using (sqlConnection = getSqlConnection())
  {
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = cmdShowEmployees;
    SqlDataReader reader = sqlCommand.ExecuteReader();
    while (reader.Read()) {
      id.Add(reader[0].ToString());
    }
    return id;
  }
}

and here

public List<string> showAllActiveData()
{
  List<string> active = new List<string>();
  using (sqlConnection = getSqlConnection())
  {
    sqlCommand.Connection = sqlConnection;
    sqlCommand.CommandText = cmdShowEmployees;
    SqlDataReader reader = sqlCommand.ExecuteReader();
    while (reader.Read()) {
      active.Add(reader[1].ToString());
    }
    return active;
  }

I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.

I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.

SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";

Any ideas?


Solution

  • If you must use the reader in this way, why not create an object which holds the table row data.

    public class SomeComplexItem
    {
        public string SomeColumnValue { get; set;}
        public string SomeColumnValue2 { get; set;}
        public string SomeColumnValue3 { get; set;}
        public string SomeColumnValue4 { get; set;}
    }
    

    That way you can loop through with your reader as follows:

    public List<SomeComplexItem> showAllActiveData()
    {
        List<SomeComplexItem> active = new List<SomeComplexItem>();
        using (sqlConnection = getSqlConnection())
        {
            sqlCommand.Connection = sqlConnection;
            sqlCommand.CommandText = cmdShowEmployees;
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                var someComplexItem = new SomeComplexItem();
                someComplexItem.SomeColumnValue = reader[1].ToString();
                someComplexItem.SomeColumnValue2 = reader[2].ToString();
                someComplexItem.SomeColumnValue3 = reader[3].ToString();
    
                active.Add(someComplexItem);
            }
            return active;
    
        }