Beruflich Dokumente
Kultur Dokumente
List. Create, Read, and Update operation are very easy to maintain the List but
Delete is difficult because List is automatically rearrange the elements after
deleting item[s].
A month ago, we have faced problem while deleting items from List in one of the
projects.
From the current page, we need to delete the items from List whose rows are
checked.
A list has object type “Item” having fields “ID” and “ItemName”.
Initial Data:
ID Item Name
Select 2 Item2
4 Item4
5 Item3
12
Fig 1.2 Expected output
Problems:
2. Delete item[s] from list by finding the index of the object and remove the
item from the list using searched index.
Find the index of the object using “List.FindIndex” for each founded object.
OR
Use method “List.FindAll” which returns array of matching records and then
use “List.FindIndex” for matched objects.
In our case, single item found [1,”Item1”] and its index is “0”.
In our case, 2 items found [3,”Item3”] and [5,”Item3”] with index is “1” and
“3” respectively.
Problems:
We can also write the logic for preventing the unexpected result.
So, I have written the logic to delete the items in any scenario and achieved the
expected result.
a. Take variable which stores the number removed items from that list.
int itemsRemoved = 0;
e. Complete Source:
int itemsRemoved = 0;
List<Item> listObject = GetItems();
for (int i = 0; i < gridObject.Rows.Count; i++)
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
int removedIndex = i - itemsRemoved +
(gridObject.PageIndex * gridObject.PageSize);
itemsRemoved ++;
listObject.RemoveAt(removedIndex);
}
}
//RefreshGrid again so changes are reflected;
c. Now, using for/foreach delete the item from the list using
“List.RemoveAt (index)”.
foreach (int k in indexList)
{
listObject.RemoveAt(k);
}
b. Now, for each item find the index and delete it from the list using
“List.RemoveAt (index)”.
a. Select any property whose type is string and insert any special
character at first position that has been never occurred in the property.
Let’s say ”>“
int startIndex = gridObject.PageIndex * gridObject.PageSize;
for (int i = 0; i < gridObject.Rows.Count; i++)
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
listObject[startIndex + i].Name = ">" + listObject
[startIndex + i].Name;
}
}
2. If you want to display deleted items before removing it then use the Third
method.