Help With DataTable

I have a simple question (hopefully)...

I need a DataTable to iterate through its result set and include the schema information of the column headers.

For instance

"SELECT x, y, z FROM MyTable"

x = Value, y = Value, z = Value

I need the values to be seperate entities (i.e. I can't have "x = Value" as a concatentated string)

I think this is a simple fix, thanks for any tips and examples.
LVL 1
clickclickbangAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Expert1701Commented:
Is this what you are looking for?

  System.Data.DataTable table;
  //...
  string select = "SELECT ";
  foreach(System.Data.DataColumn column in table.Columns)
    select += (select=="SELECT " ? "" : ", ") + column.ColumnName;
  select += " FROM " + table.TableName;
mjmarlowCommented:
// Create a buffer to hold text representation of datatable
System.Text.StringBuilder buffer = new System.Text.StringBuilder();

/*
*  Create a prototype format string for each row.
*  in the form of
*     column1 = {0},column2={1},... <cr>
* */
System.Text.StringBuilder lineprototype = new System.Text.StringBuilder();
const string template = "{0}={{{1}}},";
for(int j=0; j < dt.Columns.Count;j++)
      lineprototype.AppendFormat(template,dt.Columns[j].ColumnName,j);
lineprototype[lineprototype.Length-1] = '\n'; // replace last char with line break.
string lineproto = lineprototype.ToString();

/*
* Interate over the dataTable's Rows collection
* appending the data into the buffer using the prototype
* and the items in the Row's ItemArray
* */
for(int j=0; j < dt.Rows.Count; j++)
      buffer.AppendFormat(lineproto,dt.Rows[j].ItemArray);

return buffer; // returns a StringBuilder

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
clickclickbangAuthor Commented:
Thanks
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.