Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Data from SQL and putting in a list

Tags:

c#

.net

sql

I am getting data from SQL and putting it in list. here's what I am trying now,

public class Fruit //custom list
{
     public string aID { get;set; }  // can be more then 1
     public string bID { get;set; }  // only 2 but different aID
     public string name { get;set; } // only 1 for selection of aID and bID
}

and this is how i am getting data from sql,

var Fruitee = new Fruit();

using (SqlConnection cn = new SqlConnection(CS()))
{
      cn.Open();
      SqlCommand sqlCommand= new SqlCommand("SELECT * FROM myTable", cn);
      SqlDataReader reader = sqlCommand.ExecuteReader();
      while (reader.Read())
      {
             Fruitee.add(reader["aID"], reader["bID"],reader["name"]) // ??? not sure what to put here  as add is not available
      }
      cn.Close();
}

Table looks like this,

aID, bID, name

**

  • Problem

**

I am stuck how to add items to list and also is it best practice ?

like image 959
Mathematics Avatar asked May 31 '13 11:05

Mathematics


People also ask

How do I retrieve data from SQL Server to SharePoint list?

Create a query that selects data from an SQL database table and appends it to a SharePoint list. Click on the Query Design button under the CREATE tab and select the SQL database table. Click on the Append button under the ribbon DESIGN tab to append data to the SharePoint list.

Can you extract data from SQL?

SQL Database Extraction From a Single Table. You can use the SELECT statement with the FROM and WHERE clauses to extract data from one table. The SELECT clause specifies the fields containing the data you want to extract or display.

How do you create a list in SQL query?

You can create lists of SQL Query or Fixed Data values . In the Data Model components pane, click List of Values and then click Create new List of Values. Enter a Name for the list and select a Type.

How can I retrieve data from SQL database?

In SQL, to retrieve data stored in our tables, we use the SELECT statement. The result of this statement is always in the form of a table that we can view with our database client software or use with programming languages to build dynamic web pages or desktop applications.


2 Answers

List<Fruit> fruits = new List<Fruit>();

while (reader.Read())
{
    Fruit f = new Fruit();
    f.aID = (string) reader["aID"];
    f.bID = (string) reader["bID"];
    f.name = (string) reader["name"];
    fruits.Add(f);
}
like image 129
juergen d Avatar answered Oct 11 '22 00:10

juergen d


var list = new List<Fruit>();

  while (reader.Read())
  {
         list.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() });
  }
like image 43
Azhar Khorasany Avatar answered Oct 10 '22 22:10

Azhar Khorasany