Read data from DataTable - C#

This is the example of reading data from datatable :

The code explaination :

The code will retrieve data from database and store into databable. Andthen , the code will continue by looping each row in a datatable and try to read every column on the row.

The Code

    using System;
    using System.Data;
    using System.Data.SqlClient;

    class PopDataset
    {
       static void Main()
       {
          string connString = "<connection string>";
          string sql = "select * from employee";
          SqlConnection conn = new SqlConnection(connString);

          try
          {
         DataTable dt = new DataTable();
             conn.Open();
             SqlDataAdapter da = new SqlDataAdapter(sql, conn);  
             da.Fill(dt);
         conn.Close();            
             foreach (DataRow row in dt.Rows)
             {
        //read each column in row
                foreach (DataColumn col in dt.Columns)
        {
                   Console.WriteLine(row[col]);
        }
             }
          }
          catch(Exception e)
          {
             Console.WriteLine("Error: " + e);
          }
          finally
          {
             conn.Close();
          }
       } 
    }

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example