Get the details of columns for a given table using ADO.Net Connection
Code can be downloaded here: Download
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();
}
}
}