سؤال

I need to convert a few rows of data I am pulling from a DataTable from a List into a string separated by commas. Here is what I have now. It does not work at all (it shows System.Data.DataRow,System.Data.DataRow in the messagebox), however a breakpoint at list shows the correct number of rows, with the correct data.

cmd3.Fill(badnum);

List<DataRow> list = badnum.AsEnumerable().ToList();
string badnumbers = string.Join(",", list);
MessageBox.Show(badnumbers);
هل كانت مفيدة؟

المحلول

Your issue lies in how you're using DataRow.
DataRows contain multiple values.

The typical use is referencing a particular column within the row.

E.g. dataRow["MyColumnName"] or by index dataRow[0]

نصائح أخرى

string.Join() needs a string[] or an IEnumerable<string>

Try this:

List<DataRow> list = badnum.AsEnumerable().ToList();
string badnumbers = string.Join(",", list.Select(r=>r["MyColumn"].ToString()).ToArray());
MessageBox.Show(badnumbers);

You don't need to convert to list. You can convert each row to csv as follows

    foreach (DataRow dr in badnum.Rows)
        string csv = String.Join(",", row.ItemArray);

Something like this ought to do you:

static void Main( string[] args )
{
  const string connectString = "Server=localhost;Database=sandbox;Trusted_Connection=True;";

  DataTable dt = new DataTable() ;
  using ( SqlConnection conn = new SqlConnection(connectString) )
  using ( SqlCommand cmd = conn.CreateCommand() )
  using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
  {
    cmd.CommandText = @"select * from sys.objects" ;
    cmd.CommandType = CommandType.Text; 
    conn.Open();
    int rows = sda.Fill(dt) ;
  }

  Func<string,string> qt = x => "\"" + x.Replace("\"","\"\"") + "\"" ;

  DataRow dr = dt.Rows[0] ;
  string csv = dt.Columns
                 .Cast<DataColumn>()
                 .Select( c => qt(c.ColumnName) + "=" + qt(dr[c].ToString()) )
                 .Aggregate( (acc,s) => acc + "," + s )
                 ;
  Console.WriteLine(csv) ;

  return ;
}

Define your own semantics for what the row should look like.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top