SharePointAds TextOnly

Thursday, 27 August 2009

Sharepoint: How to get MAX id of list?

How can we get MAX id of any present list?
-> Simplely use following code
(*Note: insert your list name rather ' List_Name ')

public string MaxListId()
{
SPWeb web = SPContext.Current.Web;
SPList oList = web.Lists[" List_Name "];
SPQuery query = new SPQuery();

query.Query = " ";
SPListItemCollection items = oList.GetItems(query);

DataTable dtmax = new DataTable();
dtmax = items.GetDataTable();

string maxId = "";
foreach (DataRow row in dtmax.Rows)
{
maxId = row["ID"].ToString();
break;
}

return maxId;
}


--

1 comment:

  1. Andy Diericks

    There is errors in the procedure, you got the ID of the first splistitem in the datatable...

    Here is how you can do.

    public static int GetMaxID(SPList list)
    {
    int result = 0;
    int temp = 0;
    SPQuery query = new SPQuery();
    query.Query = "";
    SPListItemCollection items = list.GetItems(query);

    DataTable dtmax = new DataTable();
    dtmax = items.GetDataTable();

    string maxId = string.Empty;
    foreach (DataRow row in dtmax.Rows)
    {
    temp = Convert.ToInt32(row["ID"].ToString());

    if (temp > result)
    {
    result = temp;
    }
    }
    return result;
    }

    Reply Delete