we learnt the C# code for setting the properties of DataColumn. There we also learnt how to create an AutoIncrement Identity column with DataType as integer and other column with DataType as string. Here we will learn how to Add ASP.Net DataColumn to a DataTable.
Initializing ASP.Net DataTable Class Object
DataTable myDataTable = new DataTable();
Above C# code line shows how to initialize an instance for DataTable class object to create an in-memory table schema.
C# Code to Add ASP.Net DataColumn to a DataTable
// Initialize a DataTableDataTable myDataTable = new DataTable();
// Initialize DataColumn
DataColumn myDataColumn = new DataColumn();
// Add First DataColumn// AllowDBNull propertymyDataColumn.AllowDBNull = false;
// set AutoIncrement property to truemyDataColumn.AutoIncrement = true;
// set AutoIncrementSeed property equal to 1myDataColumn.AutoIncrementSeed = 1;
// set AutoIncrementStep property equal to 1myDataColumn.AutoIncrementStep = 1;
// set ColumnName property to specify the column namemyDataColumn.ColumnName = "auto_ID";
// set DataType property of the column as IntegermyDataColumn.DataType = System.Type.GetType("System.Int32");
// set Unique property of DataColumn to true to allow unqiue value for this column in each rowmyDataColumn.Unique = true;
// Add and Create a first DataColumnmyDataTable.Columns.Add(myDataColumn);
Above C# code will add and create a new auto incrementing DataColumn to the DataTable.
// Add second DataColumn
// initialize a new instance of DataColumn to add another column with different properties.myDataColumn = new DataColumn();
myDataColumn.ColumnName = "firstName";
// set DataType property of the column as StringmyDataColumn.DataType = System.Type.GetType("System.String");
// Add and Create a Second DataColumnmyDataTable.Columns.Add(myDataColumn);
// Add third DataColumn
// initialize a new instance of DataColumn to add another column with different properties.myDataColumn = new DataColumn();myDataColumn.ColumnName = "lastName";
// set DataType property of the column as StringmyDataColumn.DataType = System.Type.GetType("System.String");
// Add and Create a Third DataColumnmyDataTable.Columns.Add(myDataColumn);Note: ASP.Net DataTable creates the schema for DataColumn in the same order in which they are added to the table. For example in the above sample code DataTable will create DataColumn in the order of auto_ID, firstName, lastName.
No comments:
Post a Comment