DataTable programmatically steps - ADO.NET

Q.  What are the steps to create a DataTable programmatically?
- Published on 28 Jul 15

a. Instantiate a new DataTable and add DataColumn objects to the DataTable. Columns Collection.
b. Run the Data Source Configuration Wizard.
c. Instantiate a new DataSet object.
d. None of the above.

ANSWER: Instantiate a new DataTable and add DataColumn objects to the DataTable. Columns Collection.
 

    Discussion

  • Digvijay   -Posted on 19 Oct 15
    Example: For creating datatable programmatically you can refer the given example.
    public void CreateTable()
    {
    try
    {
    DataTable dtObj = new DataTable("Product");
    DataColumn dc = new DataColumn();
    DataRow dr;
    dc.ColumnName = "ProductID";
    dc.DataType = Type.GetType("System.Int32");
    dtObj.Columns.Add(dc);
    dc = new DataColumn();
    dc.ColumnName = "ItemName";
    dc.DataType = Type.GetType("System.String");
    dtObj.Columns.Add(dc);
    for (int i = 0; i <= 4; i++)
    {
    dr = dtObj.NewRow();
    dr["ProductID"] = i;
    dr["ItemName"] = "Item " + i;
    dtObj.Rows.Add(dr);
    }
    GridView1.DataSource = dtObj;
    GridView1.DataBind();
    }
    catch(Exception ex)
    {
    Label1.Text = ex.Message;
    }
    }

Post your comment / Share knowledge


Enter the code shown above:
 
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)