Copying results from database into a datatable and genric type

rahul kumar 605 Reputation points
2023-11-07T10:07:18.0066667+00:00
 DataTable dt = new DataTable();  
            dt = connection.FillDataGridView($"SELECT * FROM nameswithbalance").Tables[0];
            dt.TableName = "originaltable";

            dataGridView1.DataSource = dt; 


How can i modify the above the code so that i can create a generic type variable (like dictionary or something ) which can hold the data that's coming from the nameswithbalance table

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,892 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,933 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 45,271 Reputation points Microsoft Vendor
    2023-11-07T10:31:19.3+00:00

    Hi @rahul kumar , Welcome to Microsoft Q&A,

    Essentially, what you query is a datatable, and you can do all the operations that a datatable can do on it. as follows:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    
    class Program
    {
        static void Main()
        {
            DataTable dt = new DataTable();
            dt = connection.FillDataGridView($"SELECT * FROM nameswithbalance").Tables[0];
            dt.TableName = "originaltable";
    
            List<Dictionary<string, object>> data = DataTableToDictionaryList(dt);
    
            // Now 'data' contains the data from the "nameswithbalance" table in a list of dictionaries.
        }
    
        // Convert a DataTable to a List of Dictionaries
        static List<Dictionary<string, object>> DataTableToDictionaryList(DataTable dt)
        {
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
    
            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> rowData = new Dictionary<string, object>();
    
                foreach (DataColumn col in dt.Columns)
                {
                    rowData[col.ColumnName] = row[col];
                }
    
                dataList.Add(rowData);
            }
    
            return dataList;
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.