

Navigator : Home > Tutorials > Controls Tutorials > ...
Create data table in ASP.NET 2.0(C#)
This tutorial will show you how to create data table without SQL server in ASP.NET 2.0 and C#. This is very useful for storing temporary data.
Add a GridView control, two lable controls, three textbox controls and button control in the page
Create datatable structure.
private DataTable CreateDataTable() {
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "id"; myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "username"; myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "firstname"; myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "lastname"; myDataTable.Columns.Add(myDataColumn);
return myDataTable; } |
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Insert data into datatable.
private void AddDataToTable(string username,string firstname,string lastname,DataTable myTable) {
DataRow row;
row = myTable.NewRow();
row["id"] = Guid.NewGuid().ToString(); row["username"] = username; row["firstname"] = firstname; row["lastname"] = lastname;
myTable.Rows.Add(row); } |
Add data to datatable which we have created
protected void btnAdd_Click(object sender, EventArgs e) {
if (txtUserName.Text.Trim() == "") {
this.lblTips.Text = "You must fill a username."; return; } else {
AddDataToTable(this.txtUserName.Text.Trim(), this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["myDatatable"]);
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; this.GridView1.DataBind();
this.txtFirstName.Text = ""; this.txtLastName.Text = ""; this.txtUserName.Text = ""; this.lblTips.Text = ""; } } |
Be noted "Session["myDatatable"] = myDt;" is important to ensure we can add new data continually until the page be closed.
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
myDt = new DataTable(); myDt = CreateDataTable(); Session["myDatatable"] = myDt;
this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView; this.GridView1.DataBind(); } } |
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Looking for the VB.NET 2005 Version? Click Here!
Looking for more ASP.NET Tutorials? Click Here!