Creating dynamic dataTable object and columns in C#.Net

Creating dynamic DataTable and Columns
    DataTable is a good control for storing data from any control or source. With it we take objects from memory and display the results in controls such as DataGridView textbox and what ever it may be, we can show the data from the data table to those controls.We have two ways to create the datatable in c#. One is Creating object dynamically. Another one is darag drop the DataTable control from visual studio toolbox to the form. Creating the dynamic datable using code is easiest way. The code to create the datatable dynamically is like bellow. By write this code you will get a dynamic datatable. Now you can use the datatable to save the data and to display it in any control as we discussed above.
You can call the dynamic datatable with the object neme which you created in the code. Here the ojbject neme is "objname".If you want to use multiple columns in that table then you can add the columns to that dynamic datatable.By creating the multiple columns to the table, you can add multiple fields to the dynamic datatable.

        DataTable tblname = new DataTable();

        tblname .Columns.Add("ProductID", typeof(int));
        tblname .Columns.Add("ProductName", typeof(string));
        tblname .Columns.Add("ProductCompany", typeof(string));
   
    With this the columns will be added to the dynamic datatable with the names ProductID,ProductName and ProductCompany with the datatypes as mentioned
in the columns creating session. 
Adding values to the Dynamic DataTable from textbox
    DataTable will save the values in datarows, so if we want to save the data first we have to create the ne row to that table and then add the values to
the datatable.Creating the datarow will be like bellow

Event : This code should write in SaveButto_Click event.   

        DataRow dr = new DataRow();

        dr = tblname.NewRow();
        dr[0] = txtPrjctId.Text.ToString();
        dr[1] =  txtPrjctName.Text;
        dr[2]=  txtPrjctCompany.Text;
        tblname.Rows.Add(dr);

I hope this code will help you.

1 comment:

  1. I will try this too. I mean this is way more fun that it appear. Thanks for sharing, All I can recommend here is Dermology anti aging cream for the oyunger looking , glowing skin.

    ReplyDelete