Reputation: 133
I want to fill datatable from text file. DataTable looks like:
| Name | Number |
|---------+-----------|
|mike | 1 |
Text file:
John 1
Alex 3
My code:
string[] lines = System.IO.File.ReadAllLines(@"qList.txt", enc);
DataTable txtDataTable = new DataTable();
txtDataTable.Columns.Add("Name");
txtDataTable.Columns.Add("Number");
DataRow dr = txtDataTable.NewRow();
string[] columns = null;
for (int j = 1; j < lines.Length - 1; j++)
{
columns = lines[j].Split(new char[] { '\t' });
dr["Name"] = columns.GetValue(0).ToString().Trim();
dr["Number"] = columns.GetValue(1).ToString().Trim();
txtDataTable.Rows.Add(dr["Name"]);
txtDataTable.Rows.Add(dr["Number"]);
}
I need to fill like this: names from the file (John, Alex) to column name and numbers from file (1,3) to column number in datatable. My code fill every row in column "Name" of the datatable.
Upvotes: 1
Views: 284
Reputation: 826
Try this:
txtDataTable.Rows.Add(dr);
OR
txtDataTable.Rows.Add(dr["Name"], dr["Number"]);
Upvotes: 1