1

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\

0

3 Answers 3

1

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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.