Avatar of Olukayode Oluwole
Olukayode Oluwole
Flag for Canada asked on

How can i convert the contents of a list into a dataset and make it available anywhere in my application

In my c# application I need to read a set of data  from a table "stateorigin"
and get it ready as a dataset  for preparing a crystal report

I have 2 scripts

My first script defines the  fields in the dataset ( see script below)

  //Creates a new dataset, 2 datatables and adds data to them
   _dsData = new DataSet("TestDataSet");

  private void CreateDataSet2()
        {
            //Creates a new dataset, 2 datatables and adds data to them
            _dsData = new DataSet("TestDataSet");

            //byte[] arrBytes;
            //System.IO.MemoryStream ms;

            using (DataTable dt = new DataTable("stateorigin"))
            {
                dt.Columns.Add("stateid", typeof(int));
                dt.Columns.Add("statedescription", typeof(string));
              
                GlobalConfig.Connection.GetStateCode_All();

                _dsData.Tables.Add(dt);
            }
         
        }

Open in new window


So basically I want to read 2 fields  stateid and statedescription  from stateorigin table

Already during the creation of my application i have  a script that get a list of these same fields BUT

into a list.  ( See  script below )

[public List<StateOriginModel> GetStateCode_All()
        {
             List<StateOriginModel> results = new List<StateOriginModel>();

            using (var conn = new NpgsqlConnection(pgrstring))
            {
                using (NpgsqlCommand command = new NpgsqlCommand("public.spstateorigincode_getall", conn))
                {
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new NpgsqlParameter("countrycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticcountry.ToUpper() });

                    var reader = command.ExecuteReader();
                   
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            StateOriginModel model = new StateOriginModel();

                           
                            if ((string)reader["StateID"] != null)
                            {
                                model.Id = (int)reader["id"];
                                model.StateID = (string)reader["StateID"];  
                                model.StateDescription = (string)reader["StateDescription"];  
                                results.Add(model);
                            }
                        }
                    }
                }
            }
            return results;
        }[/code]

Using the debugger i know that the List is populated  into a list called results

My questions are

1. Is there a way for me to  assign the contents of the list results to the dataset    _dsData

2. I need to make the contents of _dsData   available to the calling script 1
How do i define _dsData as a static class so that  i can get its data  anywhere in my application


Thanks

Olukay
C#Crystal Reports

Avatar of undefined
Last Comment
Olukayode Oluwole

8/22/2022 - Mon
Éric Moreau

Have a look at this code snippet: https://www.dotnetperls.com/convert-list-datatable
Eduard Ghergu

Hi,

If you don't have any other reason for having the results list, you can use a SqlDataAdapter for reading the data and fill the DataSet. You have a sample here:
https://www.webtrainingroom.com/adonet/dataset
Olukayode Oluwole

ASKER
Hello Mike
The topic is related to Crystal Reports  ( Please  ask Eric who will confirm
that this is a first step in creating a .NET report in Crystal Reports)

I am trying to create a dataset  that will be an input
into my CrystalReportViewer

I was trying to narrow the issue to where i currently have an error so that
the expert helping  will focus on where i have a problem

I need to get back to Eric on my efforts and how far i have gone with his suggestion

How do I progress

Thanks

Olukay
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Éric Moreau

I have already provided a link to transform a list into a datatable (and that datatable can be added to a dataset). Also the idea of Eduard to fill the dataset right from the database can also be used.
Olukayode Oluwole

ASKER
Thanks Eric for opening this thread again.

I need both the list and the DataTable so will be going with the snippet you sent

I have tried to get the data table working  with the 2 scripts below.

The first is my old list  and it then call  the new  script that should prepare the DataTable  (see below)

[] public List<StateOriginModel> GetStateCode_All()
        {
            List<StateOriginModel> results = new List<StateOriginModel>();
                       
            using (var conn = new NpgsqlConnection(pgrstring))
            {
                using (NpgsqlCommand command = new NpgsqlCommand("public.spstateorigincode_getall", conn))
                {
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new NpgsqlParameter("countrycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticcountry.ToUpper() });

                    var reader = command.ExecuteReader();
                    // Bring in Parameters to limit selection to Login.Staticcompany
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            StateOriginModel model = new StateOriginModel();

                            if ((string)reader["StateID"] != null)
                            {
                                model.Id = (int)reader["id"];
                                model.StateID = (string)reader["StateID"];  
                                model.StateDescription = (string)reader["StateDescription"];
                                results.Add(model);
                               
                            }
                        }
                    }
                }
            }
           
            DataTable table = ConvertListToDataTable(results);
            return results;
        }

        private DataTable ConvertListToDataTable(List<StateOriginModel> results)
        {
            DataTable table = new DataTable();

            // Get max columns.
            int columns = 0;
            foreach (var array in results)
            {
                if (array.Length > columns)
                {
                    columns = array.Length;
                }
            }
           
            // Add columns.
            for (int i = 0; i < columns; i++)
            {
                table.Columns.Add();
            }

            // Add rows.
            foreach (var array in results)
            {
                table.Rows.Add(array);
            }

            return table;
        }[/code]

Where I have an issue is that my list is not being seen as an array  

So array length  is zero even though it should not be  (see the 2 screens below)

Array Length being Reported as Zero
And then because array length is zero i have another error down the line (see below)

Final Error During Debug
I have tried to see how to specify that the list should be prepared as an array but i keep

having error.

Please assist to check what i might be doing wrong

Olukay
Éric Moreau

stupid question but I will ask anyway: do you have data in your list?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Eduard Ghergu

Hi,
foreach (var array in results)
            {
                table.Rows.Add(array);
            }


array is an instance of StateOriginModel class, is not an array. You can implement a method to convert a such object to an array, if you want.
Olukayode Oluwole

ASKER
Answer to the first question is YES  . The List contains data
The list has  36 rows  and below is a typical row data  as shown in the debugger
List Has data
Typical data in List But Strangely  showing Array length as Zero

The new error screen after trying Eduard suggestion is  attached below

New  Array Error after Trying Eduard Suggestion is shown below

New Error After  Eduards SuggestionI assumed Eduard wants me to comment out everything and just have what he has
in his suggestion   ie

foreach (var array in results)             {
                table.Rows.Add(array);
            }

Thats exactly what  I have done

What should i try to resolve this error

Thanks

Olukay
Eduard Ghergu

Hi,
How your method for creating an array from StateOriginModel looks like?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
Éric Moreau

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Olukayode Oluwole

ASKER
Thanks  for the suggestions

Will now go ahead to fix the last 2 steps of generating  the report.