Saturday 12 October 2013

How to Create Lookup field(dropdownlist) in sharepoint visual webpart and update its value into sharepoint list programmatically :

Here, in my code dropdownlist is a lookup field. The below code shows how to bind data to the dropdownlist and then shows how to save the data into sharepoint list Lookup field when an item is selected in dropdownlist.

Create dropdownlist in .ascx visual webpart as below:

<asp:DropDownList ID="dropdownlist" runat="server"></asp:DropDownList>

Now copy and paste below code in page load :


        string siteUrl = SPContext.Current.Web.Url;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (SPSite spsite = new SPSite(siteUrl))
                {
                    using (SPWeb spweb = spsite.OpenWeb())
                    {
                        SPList list= spweb.Lists["YourLookUpListName"];
                        SPListItemCollection items = list.GetItems();
                        dropdownlist.DataSource = items;
                        dropdownlist.DataTextField = "FieldName"; //List field holding name
                        dropdownlist.DataValueField = "FieldName"; //List field holding value
                        dropdownlist.DataBind();
                    }
                }
            }
        }

Now copy and paste below code in the button submit :


        protected void Submit_Click(object sender, EventArgs e)
        {
            using (SPSite spsite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spsite.OpenWeb())
                {
                    SPList spList = spWeb.Lists["ListName"];
                    SPListItem spListItem = spList.Items.Add();
                    spListItem["LookUpFieldName"] = Convert.ToInt32(dropdownlist.SelectedItem.Value);
                    spListItem.Update();
                 }
             }
        }

The above code works fine for all the dropdown lookup fields in sharepoint visual webpart.





No comments:

Post a Comment

Total Pageviews