views:

932

answers:

3

This Code has a problem , that I don't know what is that . this code must Delete row of gridview when selected. I set AutoGenerateSelectButton = true then write this Code that don't work and have Exception from foreach.

protected void IDeletebtn_Click(object sender, EventArgs e)
{

    foreach (GridViewRow Items in InboxGrv.SelectedRow)
    {
        var delete = from del in MDB.Messages
                     where del.Subject == Items.Cells[0].Text.ToString()
                     select del;

        foreach (var Item in delete)
        {
            MDB.Messages.DeleteOnSubmit(Item);
        }

        MDB.SubmitChanges();
    }

}

Exception :

foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.GridViewRow' because 'System.Web.UI.WebControls.GridViewRow' does not contain a public definition for 'GetEnumerator' C:\Documents and Settings\Tehrani\Desktop\MessageAdminPage\ADMIN\Inbox.aspx.cs 87 9 C:...\MessageAdminPage\

+1  A: 

THe code in the foreach (MDB.Messages.DeleteOnSubmit(Item);) modifies the collection you are iterating through. Use a for loop instead, counting down:

int deleteCount = delete.Count();
var deleteList = delete.ToList();
for(int i = deleteCount - 1; i > 0; i--)
{
  MDB.Messages.DeleteOnSubmit(deleteList[i]);
}
Colin
this exception from your Code :Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
mohammad reza
sorry, change >= to >
Colin
I use Break point and see deleteOnsubmite don't work
mohammad reza
see edit, changed code a bit
Colin
A: 

Try to change your linq query:

string subject = Items.Cells[0].Text.ToString()
var delete = from del in MDB.Messages
                     where del.Subject == subject
                     select del;

Linq2X tries to translate this expression tree into a SQL Statement. But it don't now how to handle a Items.Cells collection. If you save the string in a local variable then Linq would see a constant.

EDIT: Ah! I was so focused on the Linq Statement that I dindt see, that GridView does not support multiple selected items.

protected void IDeletebtn_Click(object sender, EventArgs e) 
{

    foreach (GridViewRow Items in InboxGrv.SelectedRow)
    {

SelectedRow is a Object, not an enumeration.

Arthur
thisexception repeat again
mohammad reza
A: 

The exception is thrown because you are iterating an object that is not a collection. The InboxGrv.SelectedRow is the selected GridViewRow object.

Since, now you already have the GridViewRow object you can find the Id (PK) from the Row to delete the record in the database.

azamsharp