What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 33563 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to create datatable programmatically from a string using C#?

How to create datatable programmatically from a string using C#?

2 vote(s)
Rating: 4 out of 5
Article posted by Muhilan on 6/16/2010 | Views: 17410 | Category: ASP.NET | Level: Beginner red flag


In this article explain you how to create datatable programmatically from a string using C#.

Introduction

ASP.Net Gridview or other data bound controls are to filled by Dataset or DataTable. Sometimes data's not get from a datasource or data base but we need to take from other source like file system , text file , string etc..  and need to display that data into data bound controls.

 

In that scenarios need to create datatable programmatically or dynamically and filled with rows, columns and bind into the datagrid.

 

I have written simple way to create datatable programmatically based on a string.  


 

String

String looks like below , it have column product values and column Sub plan values



1. First to split the given into columns

The above screen the 4th element is Product column values and the 5th element is corresponding sub plan values. Means sub plan may have several values for a single product.

2. So again if we split into 4th element we can get 4 products like this

zero th element is product and their corresponding values will be get in another split function like this

 


In this first product have only one subplan but 2nd element have multiple suplans

DataTable Creation

declare the datatable, datarow

DataTable tmpTable = new DataTable();
        DataColumn column;
        DataRow row;

 

create datacolumn with columnname, datatype and few properties for that particular datacolumn and add to the datacolumn collections

column = new DataColumn();
column.ColumnName = "Product";
column.ReadOnly = true;
column.Unique = false ;
tmpTable.Columns.Add(column);


 In these examples created datatable with three columns

 

 column = new DataColumn();
            column.ColumnName = "Product";
            column.ReadOnly = true;
            column.Unique = false ;
                   tmpTable.Columns.Add(column);

 

            column = new DataColumn();
            column.ColumnName = "SubPlan";
            column.AutoIncrement = false;
            column.Caption = "Sub Plan";
            column.ReadOnly = false;
            column.Unique = false;
                       tmpTable.Columns.Add(column);


            column = new DataColumn();
            column.ColumnName = "NoofPolicy";
            column.AutoIncrement = false;
            column.Caption = "NoofPolicy";
            column.ReadOnly = false;
            column.Unique = false;
           tmpTable.Columns.Add(column);

Now split into string and assign values to the corresponding columns

 

  string[] tmpstr = str.Split(Convert.ToChar(254));
            string[] tmpstr2;// = new string[100];
            string[] tmpstr3;// = new string[100];

           tmpstr2 = tmpstr[3].Split(Convert.ToChar(253));//Product
           tmpstr3 = tmpstr[4].Split(Convert.ToChar(253));// subplan
            int CntMain=0,CntSub=0;
            string product = string.Empty;
            string subplan = string.Empty;

            while (CntMain < tmpstr2.Count())
            {
                product = tmpstr2[CntMain].ToString();
                subplan = tmpstr3[CntMain];
                string[] tmpsubPlan = subplan.Split(Convert.ToChar(252));
                CntSub = 0;
                while (CntSub < tmpsubPlan.Count())
                {
                        row = tmpTable.NewRow();
                        if (CntSub == 0)
                            row["Product"] = product;
                        else
                        row["Product"] = "";

                        row["SubPlan"] = tmpsubPlan[CntSub].ToString();
                        tmpTable.Rows.Add(row);
              
                    CntSub++;
                }
                CntMain++;

            }

 

Complete Code Listing

private DataTable CreateTable(string str)

{

DataTable tmpTable = new DataTable();

DataColumn column;

DataRow row;

try

{

column = new DataColumn();

column.ColumnName = "Product";

column.ReadOnly = true;

column.Unique = false ;

tmpTable.Columns.Add(column);

column = new DataColumn();

column.ColumnName = "SubPlan";

column.AutoIncrement = false;

column.Caption = "Sub Plan";

column.ReadOnly = false;

column.Unique = false;

tmpTable.Columns.Add(column);

column = new DataColumn();

column.ColumnName = "NoofPolicy";

column.AutoIncrement = false;

column.Caption = "NoofPolicy";

column.ReadOnly = false;

column.Unique = false;

tmpTable.Columns.Add(column);

string[] tmpstr = str.Split(Convert.ToChar(254));

string[] tmpstr2;// = new string[100];

string[] tmpstr3;// = new string[100];

tmpstr2 = tmpstr[3].Split(Convert.ToChar(253));//Product

tmpstr3 = tmpstr[4].Split(Convert.ToChar(253));// subplan

int CntMain=0,CntSub=0;

string product = string.Empty;

string subplan = string.Empty;

while (CntMain < tmpstr2.Count())

{

product = tmpstr2[CntMain].ToString();

subplan = tmpstr3[CntMain];

string[] tmpsubPlan = subplan.Split(Convert.ToChar(252));

CntSub = 0;

while (CntSub < tmpsubPlan.Count())

{

row = tmpTable.NewRow();

if (CntSub == 0)

row["Product"] = product;

else

row["Product"] = "";

row["SubPlan"] = tmpsubPlan[CntSub].ToString();

tmpTable.Rows.Add(row);

CntSub++;

}

CntMain++;

}

return tmpTable;

}

catch

{

// return null;

throw;

}

}

The above function return the datatable and assign to the datagrid

DataTable tmpDataTable= CreateTable(PTRN);

gvMenu.DataSource = tmpDataTable;

gvMenu.DataBind();

PTRN is a string which have the datatable values and should be


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Muhil an

Experience:3 year(s)
Home page:
Member since:Monday, November 30, 2009
Level:Starter
Status: [Member]
Biography:working as an IT System Analyst,tmuhilan at gmail com
>> Write Response - Respond to this post and get points
Related Posts

In this article we will touch base some important concepts of handling concurrency in LINQ to SQL. We will first see how LINQ supports optimistic concurrency and then we will see what support LINQ provides to handle concurrency violation. We will then touch base on some fine tuning features provided by LINQ at field level and finally we will end this article by discussing two important error reporting options when concurrency conflict happens.

It is very frequntly asked question in any of the forum or question-answer section on websites. So I decided to write a very compact article with source code. It is as simple as 123.

I am going to explain how to build dynamic menus using XMLDataSource Asp.Net ,vb.net.

To perform CRUD operation (create, read, update and delete) operation with GridView, we can follow this approach.

In this article i will demonstrate a simple online exam to with a java script timer.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 6:33:13 AM