Hi, I have a data table having data from DB
I need to add one more column and data to that table from a .txt file.
when i ran my code that new colum not coming as a first colum and and a extra column without any data is added in to the data table.
Please anyone help
my .txt file is like
NAME
----
val1
val3
val5
i need to have NAME column as 0th colum of data table.below is my code
if (tableName == "NewData")
{var pathC = @"D:\files\Data\names.txt";var fileContents = File.ReadAllLines(pathC);var splitFileContents = (from f in fileContents select f.Split(':')).ToArray();int maxLength = (from s in splitFileContents select s.Count()).Max();for (int i = 0; i < maxLength; i++)
{
table.Columns.Add();
}foreach (var line in splitFileContents)
{
DataRow row = table.NewRow();
row.ItemArray = (object[])line;
table.Rows.Add(row);
}
return table; //NAMES column will be the first column}
Sachin SinghPosted Dec 9, 2021, 4:04 PM
Sujeet RamanPosted Dec 9, 2021, 12:09 PM
Hi but i am getting index out of array exception.How we will fix?
this is what i have tried
if (tableName == "TestData")
{
var pathC = @"H:\files\Data\names.txt";
string[] result = File.ReadAllLines(pathC);
// string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
DataColumn Col = table.Columns.Add("Name", typeof(String));
Col.SetOrdinal(0); // set column to first position
int i = 0;
foreach (DataRow row in table.Rows)
{
//need to set value to NewColumn column
row["Name"] = result[i]; // INDEX OUT OF EXCEPTION HERE
i++;
}
}
Sachin SinghPosted Dec 9, 2021, 10:45 AM
Sujeet RamanPosted Dec 9, 2021, 10:43 AM
if am not using stream reader (its a console app attached to main project) how can i change
string[] strResult = File.ReadAllLines(@"C:\\file.txt"); this will work?
using (StreamReader sr = new StreamReader(@"D:\files\Data\names.txt"))
{
string strResult = sr.ReadToEnd();
string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Sachin SinghPosted Dec 9, 2021, 10:22 AM
Sujeet RamanPosted Dec 9, 2021, 9:05 AM
hari
shiju
sam
Sachin SinghPosted Dec 9, 2021, 8:56 AM
Sachin SinghPosted Dec 9, 2021, 6:49 AM
Nitin SontakkePosted Dec 9, 2021, 6:39 AM
I believe that the example you have shown is bit misleading.
Please try to give the data in the question closest to the reality.
For example, one would ask why are you spliting the line with : when there is no colon in the line.
While adding columns, you are not giving names.
First I thought that you wanted to add a column which is NOT available in the source. But I don't think that is the case.
Please provie maximum information, closest to the reality. If we make any assumptions, our answers will obviously be wrong.
You can even send a meeting request on nitin.n.sontakke at gmail dot com and we can discuss on Google Meet.
Sujeet RamanPosted Dec 9, 2021, 4:59 AM
Srinivasan RamamoorthiPosted Dec 9, 2021, 4:46 AM
Nitin SontakkePosted Dec 9, 2021, 4:07 AM