Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i was trying to add a data column to a data table from a text file but i am getting an error like this .I have tried to convert to list also but still is not working

What I have tried:

var contents = File.ReadAllText(filename).Split('\n');    
var csv = from line in contents    
          select line.Split(':').ToArray();    
    
 DataColumn Col=dt.Columns.Add("Name", typeof(String));  
  Col.SetOrdinal(0); // set column to first position  
int i=0;    
foreach(DataRow row in dt.Rows)    
{    
    //need to set value to NewColumn column    
    row["Name"] = csv[i];   // here is the issue.Tolist also not working
  i++;    
}  
Posted
Updated 17-Dec-21 6:36am
Comments

1 solution

The problem is that csv isn't an array - if you hover the mouse over it, its an IEnumerable<string[]> - an enumerable collection of arrays of strings.
You can convert that to an array of array of strings by adding brackets:
C#
var csv = (from line in contents
           select line.Split(':')).ToArray();
But that won't help you either: you are splitting a collection of items to create it, and that produces an array of strings - you need to decide which of those strings you are trying to use as the Name column data for your DataTable.

I'd start by looking at your file and thinking about what it contains: it probably isn't what you expect, especially given that "csv" normally stands for "comma delimited vales" and you are splitting on ":".

Sorry, but we can't do any of that for you: we have no idea what your file contains!
 
Share this answer
 
Comments
[no name] 9-Dec-21 4:15am    
MY  .txt   FILE IS NOT COMMA SEPERATED FILE.JUST LINE BY LINE. LIKE,

 NAME
val1
val3
val5
[no name] 9-Dec-21 4:16am    
in my D drive i have this .txt file.This is what i need to add
[no name] 9-Dec-21 4:18am    
not comma seperated just line by line
OriginalGriff 9-Dec-21 4:28am    
So first off, change your variable name - if it isn't CSV data, your code should *not* imply it is!
Second, why are you splitting it at all, if it contains no colon characters? That does nothing useful, it just returns each line of the file as a separate array containing a single element!

You need to think about your data, instead of assuming it's "such-and-such" - for example, you can't use a foreach easily, because the first line appears to be a header instead of a data row ...

And you don't need to read the file and split it on a newline anyway: File.ReadAllLines returns an array of all the lines in the file in one instruction ...
[no name] 9-Dec-21 4:43am    
i tried that also but not working

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900