Wednesday, March 9, 2011

Get Columns Schema using ADO.Net connection

Get the details of columns for a given table using ADO.Net Connection

public DataTable GetTableColumns(string strConnection, string strTableName)
     {
         //Create connectionstring
         SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder( strConnection);
         SqlConnection con = null;
         try 
         {
             con = new SqlConnection(builder.ConnectionString);
             con.Open();
 
             // As my requirement was to just list out the columns for a table, I have used top 1 *
             SqlCommand cmd =  new SqlCommand("Select top 1 * from " + strTableName, con);
             SqlDataReader rd = cmd.ExecuteReader();
 
             //Get the Schema for the given table
             return rd.GetSchemaTable();
             
         }
         catch (Exception ex)
         {
             throw new Exception(ex.Message + ex.StackTrace);
         }
         finally
         {
             if (con != null)
             {
                 con.Dispose();
             }
         }
 
         
     }
 
Code can be downloaded here: Download

No comments:

Post a Comment

Access to XMLHttpRequest at 'from origin has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. .net core angular

Issue: The angular application was getting error from API that the origin has been blocked by CORS policy. Solution: Make sure that the...