Your issue lies in how you're using DataRow
.
DataRow
s contain multiple values.
The typical use is referencing a particular column within the row.
E.g. dataRow["MyColumnName"]
or by index dataRow[0]
문제
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
.
DataRow
s 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.