Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the column data type after adding the column headers to my datatable?

Tags:

c#

datatable

Using the code below (from a console app I've cobbled together), I add seven columns to my datatable. Once this is done, how can I set the data type for each column? For instance, column 1 of the datatable will have the header "ItemNum" and I want to set it to be an Int. I've looked at some examples on thet 'net, but most all of them show creating the column header and column data type at once, like this:

loadDT.Columns.Add("ItemNum", typeof(Int));

At this point in my program, the column already has a name. I just want to do something like this (not actual code):

loadDT.Column[1].ChangeType(typeof(int));

Here's my code so far (that gives the columns their name):

// get column headings for datatable by reading first line of csv file.
        StreamReader sr = new StreamReader(@"c:\load_forecast.csv");
        headers = sr.ReadLine().Split(','); 
        foreach (string header in headers)
        {
            loadDT.Columns.Add(header);
        }     

Obviously, I'm pretty new at this, but trying very hard to learn. Can someone point me in the right direction? Thanks!

like image 309
Kevin Avatar asked Apr 02 '10 01:04

Kevin


People also ask

How do you add data to columns?

Right-click a row or column next to where you want to add data, point to Insert in the menu, and select an insertion option.

How do you add data to a DataTable?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.

Which is the title of a column in the DataTable?

The titles of columns are typically read directly from the DOM (from the cells in the THEAD element), but it can often be useful to either override existing values, or have DataTables actually construct a header with column titles for you (for example if there is not a THEAD element in the table before DataTables is ...


2 Answers

You should be able to assign the column's data type property so long as there is no data stored in that column yet:

CODE:

loadDT.Column[1].DataType = typeof(int);
like image 168
Michael Petito Avatar answered Sep 23 '22 06:09

Michael Petito


visual studio not allows to change type of a column has some data, u must create a new column with ur ideal type and copy data from specified column to new column

DataTable DT = new DataTable();
DT = somsdata ;
    DT.columns.Add("newcol",object); 
    foreach(datarow dr in DT.rows) 
             dr.itemarray["newcolumn"] = dr.itemarray["oldColumn"];
like image 27
reza akhlaghi Avatar answered Sep 25 '22 06:09

reza akhlaghi