I'm creating a custom web part in asp.net for SharePoint 2010 programmatically. When a user presses an Add button, the selected item from the dropdownlist is supposed to then be added to the Groups field of the current list. The Groups field is a lookup type from another list. Here is the code from the button event:
protected void ButtonGroup_Click(object sender, EventArgs e)
{
DeleteGroupButton1.Visible = true;
GroupLabel1.Text = ddlGroups.SelectedValue.ToString();
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Contacts"];
SPListItem listItem = SPContext.Current.ListItem;
listItem["Groups"] = new SPFieldLookupValue(SPContext.Current.ItemId, ddlGroups.SelectedValue.ToString());
listItem.Update();
}
I have tried to replace
SPListItem listItem = SPContext.Current.ListItem;
with
SPListItemCollection items = list.Items;
SPListItem listItem = items[0];
and it added the correct field from the lookup for the first item. Using an index is not desirable. In addition, the group is never updated when I go to edit it.
Clarification
I have two Lists. One is Contacts and the other is Groups. I have a Lookup column in Contacts called Groups that points to the List Groups.
Added dropdownlist population
SPList groupList = web.Lists["Groups"];
SPQuery groupQuery = new SPQuery();
groupQuery.Query = "<Query><OrderBy><FieldRef Name='Title'/></OrderBy></Query>";
SPListItemCollection groupListItemCol = groupList.GetItems(groupQuery);
foreach (SPListItem groupListItem in groupListItemCol)
{
ddlGroups.Items.Add(new ListItem(groupListItem["Title"].ToString())); //Adding Title column one by one
}
It's nested and I have omitted the rest of the code. It does populate the dropdown.