Reputation: 1368
I have a stored procedure that runs fine in SQL Server.
I call it in C# like so (with r being the first row):
DateTime beginDate = new DateTime(2016, 5, 1);
DateTime? endDate = new DateTime(2016, 5, 31);
this.getDailySalesTableAdapter.Fill(myDataSet.getDailySales, beginDate, endDate);
MessageBox.Show(rMSDataSet.getDailySales.Count.ToString()) ; //SHOWS 8549 ROWS
MYDataSet.getDailySalesRow r = myDataSet.getDailySales.First();
string mb = "";
// error here---->>>
foreach (DataColumn dc in r.ItemArray)
{
if (r[dc] != null) // This will check the null values also
{
mb = mb + r[dc] + " ";
}
MessageBox.Show(mb);
}
It compiles fine but the runtime error I get on DC is
Unable to cast object of type 'System.String' to type 'System.Data.DataColumn'
In SQL Server, my stored procedure starts:
ALTER PROCEDURE [dbo].[getDailySales]
@begindate date,
@enddate date
Upvotes: 1
Views: 101
Reputation: 12309
You need to use DataColumn.ColumnName
property:
foreach (DataColumn dc in r.ItemArray)
{
if (r[dc] != null) // This will check the null values also
{
mb = mb + r[dc.ColumnName] + " "; //Updated
}
MessageBox.Show(mb);
}
Upvotes: 3
Reputation: 27609
I would imagine that your problem is that r.ItemArray
contains strings and not DataColumn
objects. I came to this conclusion because foreach (DataColumn dc in r.ItemArray)
is the only place I can see where you are trying to cast an object to a DataColumn.
It looks like r.ItemArray is probably an object[]
(from looking at https://msdn.microsoft.com/en-us/library/system.data.datarow.itemarray(v=vs.110).aspx). So if you are wanting to just get all the values out of this you can just loop through it and look at each value.
The following code should do roughly what you want, I think. Stringbuilder idea credited to KonB from comments. It will also print out (null)
when it encounters null fields (just skipping them might be confusing when trying to work out what values are from what columns.
var mb= new StringBuilder();
foreach (object dataItem in r.ItemArray)
{
if (dataItem != null) // This will check the null values also
{
mb.Append(dataItem.ToString());
}
else
{
mb.Append("(null)");
}
mb.Append(" ");
}
MessageBox.Show(mb.ToString());
Upvotes: 1