Popular Posts

Monday, 11 July 2011

Creating a DataTable Programmatically (C#)


In given example, a datatable creates 3 columns. Each column has there datatypes.
Create function for named FillMyDataTable() for Create datatable ;
Note : Coding for .cs Class .


Private DataTable FillMyDataTable()
    {
        DataTable dt = new DataTable();
        // Here columns are defined for a datatable.
        dt.Columns.Add(new DataColumn("ID", typeof(int)));
        dt.Columns.Add(new DataColumn("Date", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("ImageURL", typeof(string)));

        // Now Create records for each column.
        DataRow dr = dt.NewRow();
        dr["ID"] = 101;
        dr["Date"] = new DateTime(2011, 11, 25);
        dr["ImageURL "] = ResolveUrl("/Images/1.jpg");
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["ID"] = 102;
        dr["Date"] = new DateTime(2011, 11, 26);
        dr["ImageURL "] = ResolveUrl /Images/2.jpg");
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["ID"] = 103;
        dr["ImageURL "] =
        dr["Date"] = new DateTime(2011, 11, 27);
        ResolveUrl("/Images/3.jpg");
        dt.Rows.Add(dr);
        return dt;
    }
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = FillMyDataTable();
            GridView1.DataBind();
        }
    }

No comments:

Post a Comment