2-Column DataTable to List<int> .NET 2.0
I have populated a DataTable from a stored procedure in an older web application written in
C# under .NET 2.0 / Visual Studio 2005.
I'm trying to populate a List with the values in the DataTable, but I keep running up against a couple issues.
My conversion process looks like this:
List<int> SpecialVendorList = new List<int>();
foreach (DataRow datarow in GetAllS开发者_如何学PythonpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
{
SpecialVendorList.Add(column["ChildVendorId"]);
SpecialVendorList.Add(column["ParentVendorId"]);
}
}
which gives me the following error:
Can not apply indexing with [] to an expression of type 'System.Data.DataColumn'
for each of the SpecialVendorList.Add() methods.
Seems like you're trying to get column values for each row. You only the first foreach
loop:
List<int> SpecialVendorList = new List<int>();
try
{
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
SpecialVendorList.Add(Convert.ToInt32(datarow["ChildVendorId"]));
SpecialVendorList.Add(Convert.ToInt32(datarow["ParentVendorId"]));
}
}
catch(FormatException fe)
{
//handle the error
}
The string index here will get that column's value in that specific row
you need to add the actual values from the rows using the column as the index:
List<int> SpecialVendorList = new List<int>();
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
{
int val;
if (int.TryParse(datarow[column].ToString(), out val))
SpecialVendorList.Add(val);
}
}
精彩评论