Developer Kinks
Developer Kinks

Reputation: 61

How can SqlDataReader fill data read in loop in asp.net

This is my code below:

SqlConnection SqlConnections = new SqlConnection();
SqlConnections.ConnectionString = Global.con;
SqlCommand SqlCommands = new SqlCommand("SELECT Id,LinkedUserID From Users");
SqlConnections.Open();
SqlCommands.Connection = SqlConnections;
SqlDataReader SqlDataReaders =   SqlCommands.ExecuteReader(CommandBehavior.CloseConnection);
while (SqlDataReaders.Read())
{
   //
}
SqlDataReaders.Close();

Im trying to run look with this code for read user id and LinkedUserID I want to all both ids for make a efface on all users as per i want please let me know how can i read both ids and return to ever single id for make a affect in database. i want to do this for use in MLM web appls during new join under any old member so i can make a affect points other user easily. any one have a idea.

Thank You

Upvotes: 0

Views: 444

Answers (1)

marc_s
marc_s

Reputation: 754328

First you need a class to hold the data you're fetching:

public class LinkData
{
   public int Id { get; set; }
   public int LinkedUserId { get; set; }
}

Then, when you iterate over your SqlDataReader, create instances of that class and store them e.g. in a List<LinkData> variable:

List<LinkData> links = new List<LinkData>();

using (SqlConnection SqlConnections = new SqlConnection(Global.con))
using (SqlCommand SqlCommands = new SqlCommand("SELECT Id,LinkedUserID From Users", SqlConnections))
{
    SqlConnections.Open();

    using (SqlDataReader SqlDataReaders = SqlCommands.ExecuteReader(CommandBehavior.CloseConnection))
    {
        while (SqlDataReaders.Read())
        {
            LinkData newItem = new LinkData();
            newItem.Id = SqlDataReaders.GetInt32(0);
            newItem.LinkedUserId = SqlDataReaders.GetInt32(1);

            links.Add(newItem);
        }

        SqlDataReaders.Close();
   }

At the end, your Links list should contain all data fetched from the database.

This is just the absolute "bare bones" solution - in your real-world code, you should probably also add some check to protect your code from crashing if one of the values is NULL in the database.

Upvotes: 2

Related Questions