0
  1. I hava records from database in DataTable.
  2. I wan't to convert the DataTable into a text.
  3. Return the text as string.

Example: Database/DataTable

id|name|age
___________
1 |Amy |17
2 |Max |23
3 |aaa |50
......

And this my code:

string result = MyFunction(MyDataTable);

MyDataTable is the DataTable and MyFunction should return this:

['id','name',age]
[['1','Amy','17']
['2','Max','23']
['3','aaa','50']]

How can I make MyFunction do this?

Eser
  • 12,346
  • 1
  • 22
  • 32
  • that's an array rather than a string, by the looks of it? What's the purpose? What do you want to do with this data? – ADyson May 06 '18 at 20:01
  • I want to load it as text from my server to my program and use it there – Abrahem haj hle May 06 '18 at 20:03
  • 1
    I suggest convert your data table contents to comma separated values (.csv) file and import it to your program. https://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv – Mohsin Mehmood May 06 '18 at 20:08
  • Mohsin Mehmood That's work Thanks! I just need time to write my code then post it here – Abrahem haj hle May 06 '18 at 20:19
  • Best way is to save datatable as Xml using the datatable method WriteXml(); – jdweng May 06 '18 at 21:07
  • jdweng that's not what I wan't there info that need name/password and lat's say I need just 1 table not all the database or more than that > where name = 'value' ... – Abrahem haj hle May 06 '18 at 21:25

1 Answers1

0

Thanks to Mohsin Mehmood I find My answer:

here the code:

string MyFunction(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                      Select(column => column.ColumnName);
    sb.AppendLine("['" + string.Join("','", columnNames) + "']");

    sb.Append("[");
    foreach (DataRow row in dt.Rows)
    {
        IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
        sb.AppendLine("['" + string.Join("','", fields) + "']");
    }
    sb.Append("]");

    return sb.ToString();
}

Then:

string result = MyFunction(MyDataTable);

Result:

['id','name',age]
[['1','Amy','17']
['2','Max','23']
['3','aaa','50']]