尝试遍历ListBox,错误:指定的强制转换无效

本文关键字:无效 转换 遍历 ListBox 错误 | 更新日期: 2023-09-27 18:04:48

我有一个方法在另一个类我用来发送数据到数据库。这个方法也在这里。

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页面上的方法,我用它来迭代我的列表框,并在列表框中的每个项目执行该方法也在这里。

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时,它会给出以下错误:

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

知道这是为什么吗?

尝试遍历ListBox,错误:指定的强制转换无效

应该是这样的

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

您正在迭代ListBox。项通过int类型字段。列表框。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的单个项目