Wednesday, October 1, 2014

How to Add Colmns to DataTable and adding Some rows to it and binding to Gridview

In aspx.cs

Adding rows using code to DataTable

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



public partial class Example : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CretaeDatatablewithrows();
        }

    }
   public void CretaeDatatablewithrows()
    {
        //Creating new instance of DataTable
        DataTable dt = new DataTable();
        //Adding columns to datatable
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Emailid", typeof(string));

        //Adding Dummy data to datatable
        for (int i = 1; i <= 10; i++)
        {
            DataRow row;
            row = dt.NewRow();
            row["Emailid"] = "dummy" + i + "@gmail.com";
            row["ID"] = i;
            dt.Rows.Add(row);
        }
        //Bind DataTable to GridView
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
}

We are creating one method that will add columns to DataTable and bind to GridView.

Compile and execute following Output will Get

OutPut:


No comments:

Post a Comment