How can I populate a list with values ​​from a SQL Server database?

The list will grow and shrink depending on the number of items that I have in my database.

I need to fill out a list, not a list. I understand that I will need to open a connection.

using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString))
{
    using (var cmd = conn.CreateCommand())
    {
        conn.Open(); 

        List<string> TagList = new List<string>();
        for (int i = 0; i < TagList.Count; i++)
            TagList[i].Add("Data from database");

        cmd.ExecuteNonQuery();
    }
}

I'm really not sure how to do this, and I'm sure my method here looks very wrong, so I really need help.

Can someone show me what I'm doing wrong?

+3
source share
3 answers
public IEnumerable<string> GetTagList()
{
    using (var connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "select Tag from TagsTable"; // update select command accordingly
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader.GetString(reader.GetOrdinal("Tag"));
            }
        }
    }
}

then you can call it below

List<string> tags = GetTagList().ToList();
+7
source

That would be as it is (if I did not make any typos ...)

private void LoadList()
    {
        List<string> tagsList = new List<string>();

        using (IDbConnection connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
        {
            connection.Open();    

            using (IDbCommand command = connection.CreateCommand())
            {
                command.CommandText = "SELECT TAGCOLUMN FROM TAGSTABLE";

                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0))
                            tagsList.Add(reader.GetString(0));
                    }

                    reader.Close();
                }
            }

            connection.Close();
        }
    }

EDIT:

, select . , , .

+3

I would like to share my solution, hope someone helps in the future:

public List<string> getFromDataBase() 
{
    List<string> result = new List<string>();
    SqlConnection con = new SqlConnection("connectionString");
    try {
        con.Open();
        DataTable tap = new DataTable();
        new SqlDataAdapter(query, con).Fill(tap);
        result = tap.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("columnName")).ToList();
    }
    catch (Exception) {
            //Exception   
    }
    finally {
        if (con != null)
            con.Close();
    }
    return result;
}
+3
source

All Articles