JARRRRG
JARRRRG

Reputation: 926

Trying to iterate through ListBox, Error : Specified cast is not valid

I have a method in another class i'm using to send data to a database. That method is here as well.

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

The method on my aspx page which i'm using to iterate through my listbox and execute that method for each item in the listbox is here as well.

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

When I run my website and hit the btnSubmit it's giving the following error :

"Specified cast is not valid" that is on the method on the aspx page (the 2nd pastebin file)

Any idea why this is?

Upvotes: 0

Views: 294

Answers (2)

Pratik Mehta
Pratik Mehta

Reputation: 1352

It should be like this

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

Upvotes: 1

Habib
Habib

Reputation: 223187

You are iterating the ListBox.Items through an int type field. ListBox.Items is a ListItemCollection, what you can do is use implicitly typed variable using var keyword, like:

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

Currently it appears you are considering it as an index in foreach loop, instead its a single item from the lstAdded

Upvotes: 0

Related Questions