read a list of values from a database in csharp

In C#, you can use ADO.NET library to read data from a relational database. Here's an example of how to read a list of values from a database using C#:

main.cs
using System.Collections.Generic;
using System.Data.SqlClient;

// Define a class to hold each row of data
class DataItem {
    public int Id { get; set; }
    public string Name { get; set; }
    // Add other properties as needed
}

// Connect to the database and execute a query
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    string query = "SELECT Id, Name FROM YourTableName";
    SqlCommand command = new SqlCommand(query, connection);

    // Read the results into a list
    List<DataItem> list = new List<DataItem>();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        DataItem item = new DataItem();
        item.Id = reader.GetInt32(0);
        item.Name = reader.GetString(1);
        list.Add(item);
    }
    reader.Close();
}
948 chars
31 lines

This code opens a connection to the database, executes a SELECT query, reads the results into a list of DataItem objects, and closes the connection. You can modify the query and the DataItem class to fit your specific needs.

gistlibby LogSnag