Saturday 9 November 2013

SqlClient - Read Data From database and store into DataTable or DataSet - C#

Leave a Comment
This tutorial show how to read database and pass the value in DataTable or DataSet. 

Requirement in this tutorial are :
  1. using System.Data.SqlClient;
  2. using System.Data;

The sample code should be like this :

            DataTable table = new DataTable();
            SqlConnection dbConn = new SqlConnection("<connection string>");
            SqlCommand dbComm = new SqlCommand("<sql statement or procedure name>", dbConn);
            
            //set command type is procedure if you are using store procedure
            //else remove this line
            dbComm.CommandType = CommandType.StoredProcedure;

            try
            {
                SqlDataAdapter dbAdapter = new SqlDataAdapter(dbComm);
                dbConn.Open();
                dbAdapter.Fill(table);
            }
            catch (SqlException sqlEx)
            {
                MessageBox.Show(sqlEx.Message);                
            }
            finally
            {
                dbConn.Close();                
            }  



Now change to store value in DataSet .

            DataSet dataSetTable = new DataSet();
            SqlConnection dbConn = new SqlConnection("<connection string>");
            SqlCommand dbComm = new SqlCommand("<sql statement or procedure name>", dbConn);
            
            //set command type is procedure if you are using store procedure
            //else remove this line
            dbComm.CommandType = CommandType.StoredProcedure;

            try
            {
                SqlDataAdapter dbAdapter = new SqlDataAdapter(dbComm);
                dbConn.Open();
                dbAdapter.Fill(dataSetTable,"<set table name here>");
            }
            catch (SqlException sqlEx)
            {
                MessageBox.Show(sqlEx.Message);                
            }
            finally
            {
                dbConn.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 =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.