I have a text file which has 7,000 data in it and i want to read the rows from file and then check it with the columns if it has right attribute or not.I don't want to write every row.I just want the line below to work from file .I don't want to write it one by one
.Row.Add(new object[]{...,...}) Please help!

Dani AI

Generated

Short answer: read the file line by line, parse each line into the same number of fields as the DataTable's columns, convert each field to the column's type (or to DBNull.Value when missing/invalid), and call DataTable.Rows.Add(object[]) inside the loop. That is exactly the loop-based approach hinted at. 's point about "attributes" maps to validating/parsing each field against the DataColumn.DataType before adding.

A minimal, practical pattern:

var table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Amount", typeof(decimal));

table.BeginLoadData();

foreach (var line in File.ReadLines("data.txt"))
{
    var parts = line.Split(',');            // use a CSV parser if fields can be quoted
    if (parts.Length < table.Columns.Count) continue;

    object[] values = new object[table.Columns.Count];

    int id;
    values[0] = int.TryParse(parts[0].Trim(), out id) ? (object)id : DBNull.Value;

    values[1] = string.IsNullOrWhiteSpace(parts[1]) ? (object)DBNull.Value : parts[1].Trim();

    decimal amt;
    values[2] = decimal.TryParse(parts[2].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out amt) ? (object)amt : DBNull.Value;

    table.Rows.Add(values);
}

table.EndLoadData();

Notes and cautions: check parts.Length to avoid index errors; use DBNull.Value for missing data; prefer File.ReadLines for streaming large files (or ReadAllLines on older runtimes). Call BeginLoadData/EndLoadData around bulk adds to skip interim constraint checks and improve speed. If the input is true CSV with quotes/commas inside fields, use a CSV parser (TextFieldParser or a library such as CsvHelper). For inserting into a database after filling the DataTable, consider SqlBulkCopy for best performance on thousands of rows.

Recommended Answers

All 2 Replies

I'm not quite sure I understand what your talking about. What kind of attribute are you looking for? What kind of data is in the text file?

Sounds like you're going to need a loop to traverse through each row? I dont know if thats what you're asking or not though because your question was quite general and hard to understand.

Reguards,

Tyler S. Breton

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.