Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Saturday, April 3, 2010

Bind GridView with Datatable

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;
}


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(parameter);
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.txtUserName.Text = "";
this.lblTips.Text = "";
}
}

// Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable myDt = new DataTable();
myDt = CreateDataTable();
this.GridView1.DataSource = myDt
this.GridView1.DataBind();
}
}