.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!



  

Create DataTable

   
 
     


Introduction :

DataTable is an important class of ADO.Net. We can use datatable as in RAM Table like database.

DataTable is an important class of ADO.Net. We can bind datatable to any controls like GridView, Dropdownlist, ListBox etc.

To add rows to a DataTable, you must first use the NewRow method to return a new DataRow object. The maximum number of rows that a DataTable can store is 16,777,216.

 In this example we will see

How to create DataTable

DataTable is present under System.Data NameSpace

C# Code Example

private DataTable GetDataTable()

{

// Create an object of DataTable class

DataTable dataTable = new DataTable("MyDataTable");

//Create ID DataColumn

DataColumn dataColumn_ID = new DataColumn("ID", typeof(Int32));

dataTable.Columns.Add(dataColumn_ID);

//Create another DataColumn Name

DataColumn dataColumn_Name = new DataColumn("Name", typeof(string));

dataTable.Columns.Add(dataColumn_Name);

//Now Add some row to newly created dataTable

DataRow dataRow;

for (int i = 0; i < 5; i++)

{

dataRow = dataTable.NewRow();// Important you have create New row

dataRow["ID"] = i;

dataRow["Name"] = "Name_" + i.ToString();

dataTable.Rows.Add(dataRow);

}

dataTable.AcceptChanges();

return dataTable;

}

VB.Net Code Example

Private Function GetDataTable() As DataTable

' Create an object of DataTable class

Dim dataTable As New DataTable("MyDataTable")

'Create ID DataColumn

Dim dataColumn_ID As New DataColumn("ID", GetType(Int32))

dataTable.Columns.Add(dataColumn_ID)

'Create another DataColumn Name

Dim dataColumn_Name As New DataColumn("Name", GetType(String))

dataTable.Columns.Add(dataColumn_Name)

'Now Add some row to newly created dataTable

Dim dataRow As DataRow

For i As Integer = 0 To 4

dataRow = dataTable.NewRow()

' Important you have create New row

dataRow("ID") = i

dataRow("Name") = "Name_" & i.ToString()

dataTable.Rows.Add(dataRow)

Next

dataTable.AcceptChanges()

Return dataTable

End Function

The above function will create DataTable with tow row ID and Name with some sample data and return DataTable

We can Bind this datatable to any gridview like this

dataGridView1.DataSource = GetDataTable();

Other Tutorials in the same Category:
      
  • Create DataTable      
  • ADO.Net      
  • Delete Row from DataTable      
  • Edit Row in DataTable      
  • A basic introduction of ADO.NET      
  • A basic introduction of ADO.NET      
  • A Basic Introduction about ADO.NET Object Model      
  • How To Creating Connection Object      
  • How to Creating Command Object

  •  
         
     
    Return to Main Index Page


    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend