简体   繁体   中英

update generic list index

This might be something really simple but after several hours coding I've gone blank. I have a generic list which I populate on page load

int newtotalrows = listdetail.Count + rowstoadd -1;
for (int i = listdetail.Count; i <= newtotalrows; i++)
{
    ArDocumentdetail detail = new ArDocumentdetail();
    detail.Lineid = i;
    detail.Itemid = 0;
    detail.Quantity = 1;
    if (listdetail.Count > 0)
        listdetail.Insert(listdetail.Count, detail);
    else
        listdetail.Add(detail);
}

ViewState["InvoiceDetail"] = listdetail;
LoadGrid();

This works fine it creates a list with

lineid | Itemid
  1        0
  2        0
  3        0

This gets bound to a gridview. In my gridview a I have a button which deletes a row Here is where my problem lies.

Lets say I delete lineid = 2 then in my gridview databound when I try to put the values in the list to the gridview control it says that it can't find the index because my list is now

lineid | Itemid
  1        0
  3        0

but my gridview reads index like this

lineid | Itemid
  1        0
  2        0  <- this use to be lineid = 3

so those indexes don't match. What I'm thinking that when I delete a row in my list that I regenerate the lineid.

if (ViewState["InvoiceDetail"] != null)
listdetail = (ListArDocumentdetail)ViewState["InvoiceDetail"];

int index = listdetail.FindIndex(f => f.Lineid == row.RowIndex);
listdetail.RemoveAt(index);
for (int i = 0; i <= listdetail.Count; i++)
{ 
    //here is where i assume it should regenerate list lineid value
}

I think what you're looking for is detail.Lineid = i; . You could start from int i = index instead of 0 , because nothing before index will have changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM