用于列表<int> .NET 2.0 的 2 列数据表



我已经从一个用

编写的旧web应用程序的存储过程中填充了一个DataTable

c# under . net 2.0/Visual Studio 2005.

我试图用数据表中的值填充列表,但我一直遇到几个问题。

我的转换过程是这样的:

List<int> SpecialVendorList = new List<int>();
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
   {
       SpecialVendorList.Add(column["ChildVendorId"]);
       SpecialVendorList.Add(column["ParentVendorId"]);
   }
}

给出如下错误:

Can not apply indexing with [] to an expression of type 'System.Data.DataColumn'
每个SpecialVendorList.Add()方法的

似乎您正在尝试获取每行的列值。您只需要第一个foreach循环:

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
}

这里的字符串索引将获取该列在特定行的值

您需要添加使用该列作为索引的行中的实际值:

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);
   }
}

最新更新