quarta-feira, 17 de outubro de 2012

Add columns to DataTable



static void Main(string[] args)
{

DataTable dt = new DataTable();

// Add the column to the DataTable to create
DataColumn col1 = dt.Columns.Add();

// Configure the column
//-- integer with a default = 0
// that  does not allow nulls
col1.ColumnName = "1Column";
col1.DataType = typeof(int);
col1.DefaultValue = 0;
col1.Unique = true;
col1.AllowDBNull = false;

// Create  the column
DataColumn col2 = new DataColumn();

// Configure the column
//string with max length = 50
col2.ColumnName = "2Column";
col2.DataType = typeof(string);
col2.MaxLength = 50;


// Add column to the DataTable
dt.Columns.Add(col2);

// Add a column directly using an overload of the Add()
 // method of the DataTable.Columns collection -- the column
 // is a string with max length = 50
dt.Columns.Add("3Column", typeof(string)).MaxLength = 50;

// Add multiple existing columns to the DataTable
DataColumn col4 = new DataColumn("4Column");

// ... configure column 5
DataColumn col5 = new DataColumn("5Column", typeof(int));

// Add columns 4 and 5 to the DataTable
dt.Columns.AddRange(new DataColumn[] { col4, col5 });

// Show the columns in the DataTable to the console
Console.WriteLine("DataTable has {0} DataColumns named:",dt.Columns.Count);

foreach (DataColumn col in dt.Columns)

Console.WriteLine("\t{0}", col.ColumnName);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}










Sem comentários:

Enviar um comentário