Skip to content

Instantly share code, notes, and snippets.

@amarodeabreu
Created February 23, 2021 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amarodeabreu/2eda168cd286e09e3fbf925481081b30 to your computer and use it in GitHub Desktop.
Save amarodeabreu/2eda168cd286e09e3fbf925481081b30 to your computer and use it in GitHub Desktop.
/// <summary>
/// Get table columns from db schema
/// </summary>
public void GetColumns()
{
// New table column class
_tableColumnsArrayList = new List<TableColumns>();
// Get db name from settings file
var database = Properties.Settings.Default.Database;
// Get selected table's columns, but leave out the TimeStamp column for readability
var sql = "USE [" + database + "] SELECT COLUMN_NAME As [Column Name], DATA_TYPE As [Data Type], CHARACTER_MAXIMUM_LENGTH As [Max Length] FROM INFORMATION_SCHEMA.COLUMNS with (nolock) WHERE TABLE_NAME = '" +
TableName + "' AND TABLE_SCHEMA = 'dbo' and COLUMN_NAME <> 'TimeStamp'";
using (var connection = new SqlConnection(ConnectionString))
{
var command = new SqlCommand(sql, connection);
connection.Open();
var reader = command.ExecuteReader();
try
{
while (reader.Read())
{
// Populate column class and add to list for later looping
_tableColumnsArray = new TableColumns
{
ColumnName = reader["Column Name"].ToString(),
DataType = reader["Data Type"].ToString(),
MaxLength = reader["Max Length"].ToString()
};
_tableColumnsArrayList.Add(_tableColumnsArray);
}
}
catch (Exception ex)
{
reader.Close();
// Show alert on error - no message boxes, using popups
var alertInfo = new AlertInfo("Error", ex.Message);
var control = new AlertControl { FormLocation = AlertFormLocation.BottomRight };
control.Show(ParentForm, alertInfo);
}
reader.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment