Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question - Foreach in Datatable - Format in Text File 1

Status
Not open for further replies.

Anddmx

Technical User
Apr 26, 2004
56
0
0
US
Hi,

I have little problem with looping through datatable and then writing it to text file. The data is coming for datatable and I want it to look just like datatable in text file.

It looks like this so far.

hotel - Marriot
city - Idaho
address - 5555 yellowstone blvd

and I want it to look like this

hotel city address

Marriot Idaho 5555 yellowstone blvd
Marriot Utah 1234 Shipply Lane
Marriot Montana 4521 Blue Dr

Code:

foreach (DataRow datarow in dt_row.Rows)
{
foreach (DataColumn dataCD in dt_row.Columns)
{

w.WriteLine(datarow[dataCD].ToString());

}

}



Thanks
 
does DataColumn have a name property then use that
like
w.WriteLine(datarow[dataCD.Name].ToString());
 
something like this.
Code:
DataTable dt = //get data;

//write column headers
foreach (DataColumn dataColumn in dt.Columns)
{
      if(dataColumn .Ordinal != 0)
      {
          w.Write("\t");
      }
       w.Write(dataColumn.ColumnName);
}
w.WriteLine(string.Empty);

//write row data
foreach (DataRow datarow in dt.Rows)
{
   foreach (DataColumn dataColumn in dt.Columns)
   {
      if(dataColumn .Ordinal != 0)
      {
          w.Write("\t");
      }
       w.Write(datarow[dataColumn.ColumnName]);
   }
   w.WriteLine(string.Empty);
}

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top