试图迭代ListBox,错误:指定的强制转换是无效的

时间:2013-03-19 04:47:22

标签: c# asp.net listbox loops

我在另一个用于将数据发送到数据库的类中有一个方法。该方法也是here

public Int32 AddOrder(clsStock NewItem)
{
    //this function takes the data passed via NewItem
    //and passes it to the parameters for the stored procedure
    //
    //create an instance of the data dictionary
    clsDataDictionary DD = new clsDataDictionary();
    //create an instance of the object class
    Int32 ReturnValue;
    //create an instance of the data conduit
    clsDataConduit Items = new clsDataConduit();
    //pass the data for this address
    Items.AddParameter(DD.sproc_tblOrders_Add_AuthId, NewItem.AuthId);
    Items.AddParameter(DD.sproc_tblOrders_Add_ItemId, NewItem.ItemId);
    Items.AddParameter(DD.sproc_tblOrders_Add_DateOrdered, NewItem.DateOrdered);
    Items.AddParameter(DD.sproc_tblOrders_Add_Cancel, NewItem.Cancel);
    //execute the stored procedure
    ReturnValue = Items.Execute(DD.sproc_tblOrders_Add);
    //return the primary key value
    return ReturnValue;
}

我的aspx页面上的方法,我用来迭代我的列表框并为列表框中的每个项目执行该方法也是here

protected void btnSubmit_Click1(object sender, EventArgs e)
{
    //create an instance of the collection class
    clsStockCollection Items = new clsStockCollection();

    foreach(int id in lstAdded.Items)
    {
        TheItem.AuthId = 5;
        TheItem.ItemId = Convert.ToInt32(lstAdded.Items[id].Value);
        TheItem.Cancel = "false";
        Items.AddOrder(TheItem);
    }
    Response.Redirect("Order.aspx");
}

当我运行我的网站并点击btnSubmit时,它会发出以下错误:

"Specified cast is not valid"位于aspx页面上的方法(第二个pastebin文件)

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

应该是这样的

foreach(ListItem item in lstAdded.Items)
{
    TheItem = new clsStock();
    TheItem.AuthId = 5;
    TheItem.ItemId = Convert.ToInt32(item.Value);
    TheItem.Cancel = "false";
    Items.AddOrder(TheItem);
}

答案 1 :(得分:0)

您正在通过int类型字段迭代ListBox.Items。 ListBox.Items是ListItemCollection,您可以使用var关键字使用隐式类型变量,例如:

foreach(var id in lstAdded.Items)
{
    TheItem.AuthId = 5;
    TheItem.ItemId = Convert.ToInt32(id.Text); //Change here
    TheItem.Cancel = "false";
    Items.AddOrder(TheItem);
}

目前您似乎将其视为foreach循环中的索引,而不是lstAdded

中的单个项目