简体   繁体   中英

asp.net C# database table column to list

I have an asp.net project done in C# (my C# syntax is very rusty) and am using the built in database it creates with the project. I've created a table called aspnet_Tutorials that (for now) stores two columns of user submitted data: TutorialName and TutorialContent. Very simple, it's a learning project.

What I need to do is create a list from the first column of aspnet_Tutorials to use it to create a "directory" of the tutorials on a page. The part I'm having trouble with, mostly syntactically, is connecting to and iterating over the column to get the values into a list. Could anyone provide a straight forward example of this? And possibly explain what's going on in the code.

public class TutorialsDirDAL
    {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();


        public List<string> DisplayTutorials() //parameters? String qry?
        {
           //query the database table, foreach loop over the data, place it into a list?
        }
    }

I know how to write simple sql queries. But I've seen a couple different set ups for this in my Googling spree. I currently have the following for a query, feel free to pick it apart or offer a better solution than using a query.

cmd.CommandText = "SELECT * FROM ASPNET_TUTORIALS (TutorialTitle)"
                + "VALUES (@tutorialTitle)";

Thank you!

Well you can fetch using data reader and map to the object. I can give you some rough code, which could be like this:

            using (IDataReader objDataReader = objDB.ExecuteReader(objCMD))
            {
                while (objDataReader.Read())
                {
                    DataBaseObject obj = new DataBaseObject();
                    obj = MapObjectToList(objDataReader);
                    ObjectList.Add(obj);

                }
                objDataReader.Dispose();
            }

// Mapping Function can be called somewhat like this:

private DataBaseObject MapObjectToList(IDataReader objDataReader)
{
    DataBaseObject obj = new DataBaseObject();
    obj.Prop1Name = base.GetDataValue<string>(objDataReader, "Column1Name");
    obj.Prop2Name = base.GetDataValue<string>(objDataReader, "Column2Name");
    return obj;
}

But this is just a rough idea how I would do it.

ebad86's answer is acceptable but since you are obviously learning I think introducing OO principals muddy the water with what you are trying to learn at this point.

Here is a basic method:

private void GetData()
{
   //The object that will physically connect to the database
   using(SqlConnection cnx = new SqlConnection("<your connection string>")
   {
            //The SQL you want to execute
           SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
           //Open the connection to the database
           cnx.Open();
           //execute your command
           using (IDataReader dataReader = cnx.ExecuteReader(cmd))
           {
             //Loop through your results
             while(dataReader.Read())
             {
                //do whatever to the data
                ListItem item = new ListItem(Convert.ToString(dataReader["TutorialName"])); 
                lst.Items.Add(item);
             }
           }
   }
}

This is all very straightforward. The part you are most interested in is the while loop though. The loop will go through all of the returned records and you can do whatever you need to do with them. In my example I have assumed that there is a ListBox named 'lst' and I am simply adding ListItems to it that will have the name of whatever 'TutorialName' is. You can make literally do whatever you need to do with the data at this point. To fit your example (returning a List) you would do this:

private List<string> GetData()
{
   List<string> lst = new List<string>();
   //The object that will physically connect to the database
   using(SqlConnection cnx = new SqlConnection("<your connection string>")
   {
            //The SQL you want to execute
           SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
           //Open the connection to the database
           cnx.Open();
           //execute your command
           using (IDataReader dataReader = cnx.ExecuteReader(cmd))
           {
             //Loop through your results
             while(dataReader.Read())
             {
                lst.Add(Convert.ToString(dataReader["TutorialName"]));
             }
           }
   }
   return lst;
}

Please respond if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM