Gridview remove items

自古美人都是妖i 提交于 2019-12-11 18:34:07

问题


I have I gridview in which the data source is a List<T>. When I try to remove an item from the gridview in my buttonRemove_Click() function another function which handles the RowDeleting event is invoked where I remove the item from the List<T> as well. The problem is that if I select to remove multiple items from the gridview the index of the gridview and that of my List<T> un-syncs. For example I have 10 items in my gridview and in my List and I try to remove the last two items. Here is how I do it in my buttonRemove_Click function

foreach (GridViewRow row in gridViewItems.Rows)
{
    CheckBox cb = (CheckBox)row.FindControl("checkBox");

    if (cb != null && cb.Checked)
    {
        gridViewItems.DeleteRow(row.DataItemIndex);
    }
}

Then in the RowDeleting function, I'll first receive the event for the index 8, I removed it. Now when it comes to deleting the last item (index 9), then it'll throw exception because the index is out of range. How do I solve this problem?

I think the problem will be solved if I try removing the rows in reverse order i.e. starting from the highest index. Can anyone tell how can this be done?


回答1:


GVGLCode1.DataSource = dt;
GVGLCode1.DataBind();

int iCount = GVGLCode1.Rows.Count;
for (int i = 0; i <= iCount; i++)
{
    CheckBox cb = (CheckBox)GVGLCode1.rows[i].FindControl("checkBox");
    if (cb != null && cb.Checked)
    { 
       GVGLCode1.DeleteRow(i);
    }
}

Please try with this. May be it can help u.



来源:https://stackoverflow.com/questions/4966755/gridview-remove-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!