0

I have an application page, which contain a listview, with a dropdownlist in it, first load of page: I have my Dropdownlist , when I select a value and hit f5 , I want to see the selected value (and have the ability to change it again)

PS : when I put autopostback = true in my dropdownlist, and I change value , the page refresh automatically and bring default value When I remove autopostback="true", and I change the value, it take it, but when I hit f5 it reload default value

this is my ascx.cs:

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using PWC.SharePoint.Common.DataObjects.Entities;
using PWC.SharePoint.Common.DataObjects.Structs;
using PWC.SharePoint.Common.Utilities;
using System.Threading;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;
using System.Web.UI;


namespace PWC.SharePoint.Common.Layouts.PWC
{
    public partial class ApprovedReassessments : LayoutsPageBase
    {
        #region ================= Properties and Variables =================
        private SPWeb currentWeb = SPContext.Current.Web;
        private const string SITESURL = "/sites/";
        private const string DROPDOWNLIBRARYFIELDS = "<FieldRef Name='{0}' /><FieldRef Name='{1}' /><FieldRef Name='{2}' /><FieldRef Name='{3}' /><FieldRef Name='{4}' /><FieldRef Name='{5}' /><FieldRef Name='{6}' />";
        private const string CAMLWHERE = "<Where>{0}</Where>";
        private const string CAMLEQAGENTID = "<Eq><FieldRef Name='AgentId'/><Value Type='Text'>{0}</Value></Eq>";
        protected DataPager ReassessmentSelectorDataPager = null;
        private const string DATATEXTFIELD = "Text";
        private const string DATAVALUEFIELD = "Value";
        /// <summary>
        /// Gets Root Site Url
        /// </summary>
        private string RootSiteUrl
        {
            get
            {
                if (this.currentWeb.ServerRelativeUrl == CALCULATION_RESULT_VALUES.BACK_SLASH)
                {
                    return this.currentWeb.Url;
                }
                else
                {
                    return this.currentWeb.Url.Replace(this.currentWeb.ServerRelativeUrl, string.Empty);
                }
            }
        }
        /// <summary>
        /// Gets or sets Last Sort Key
        /// </summary>
        private string LastSortKey
        {
           ...
        }

        /// <summary>
        /// Gets or sets Last Sort Direction
        /// </summary>
        private SortDirection LastSortDirection
        {
           ...
        }

        #endregion // ================= Properties and Variables =================




        protected void OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            List<string> listStatus = new List<string>(new string[] { "WIP", "Completed" });
            if (listStatus != null && listStatus.Count > 0)
            {
                var statList = listStatus.Select(item => new
                {
                    Text = item,
                    Value = item
                });


                DropDownList DDLStatus = (e.Item.FindControl("ddlStatus") as DropDownList);

                DDLStatus.DataSource = statList;
                DDLStatus.DataTextField = DATATEXTFIELD;
                DDLStatus.DataValueField = DATAVALUEFIELD;
                DDLStatus.DataBind();

                DDLStatus.Items.Insert(0, string.Empty);
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false)
            {

            }
        }


        /// <summary>
        /// Triggers when page is rendering
        /// </summary>
        /// <param name="e">Event Arguements</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.EnsureChildControls();

            try
            {

                this.ApprovedReassessmentsListView.DataBind();
                BindReassessmentSelectorToControl();
                this.ReassessmentSelectorDataPager.DataBind();
            }
            catch (Exception ex)
            {
                LoggingUtilities.LogToDatabase(PWC_LOG_TYPE.ERROR, ex.Message, ex.ToString(), this.currentWeb.Url, this.currentWeb.CurrentUser.LoginName);
            }
        }


        /// <summary>
        /// Rebinds Reassessment when paging property change
        /// </summary>
        /// <param name="sender">Reassessment List View</param>
        /// <param name="e">Page Properties Changing Event Arguments</param>
        protected void ReassessmentSelectorListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
         ...
        }

        /// <summary>
        /// Sorts Reassessments
        /// </summary>
        /// <param name="sender">Reassessment List View</param>
        /// <param name="e">List View Sort Event Arguments</param>
        protected void ReassessmentSelectorListView_Sorting(object sender, ListViewSortEventArgs e)
        {
          ...
        }




        /// <summary>
        /// Binds data to controls
        /// </summary>
        private void BindReassessmentSelectorToControl()
        {


            ...
        }

        /// <summary>
        /// Builds conditional statement for CAML query
        /// </summary>
        /// <param name="conditions">List of conditions</param>
        /// <returns>conditional statement</returns>
        string BuildConditions(List<string> conditions)
        {
         ...
        }

        /// <summary>
        /// Updates the Financial Assessment Status to WIP
        /// </summary>
        /// <param name="itemId">Financial Statement Item Id</param>
        private void UpdateFinancialAssessmentStatusToRTP(string agentId, string salesforceCaseNumber)
        {


          ...
    }

    protected void ddlStatus_change(object sender, EventArgs e)
    {

    }

}

}

and this is my ascx:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="True" CodeBehind="ApprovedReassessments.aspx.cs"
    Inherits="PWC.SharePoint.Common.Layouts.PWC.ApprovedReassessments" DynamicMasterPageFile="~masterurl/default.master" %>

<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.WebControls" TagPrefix="asp" %>


<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <asp:PlaceHolder ID="ApprovedReassessmentSelectorPlaceHolder" runat="server">
        <table border="0" width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    <asp:ListView ID="ApprovedReassessmentsListView" runat="server" ItemPlaceholderID="ApprovedRow" OnItemDataBound="OnItemDataBound"
                        OnSorting="ReassessmentSelectorListView_Sorting" OnPagePropertiesChanging="ReassessmentSelectorListView_PagePropertiesChanging">
                        <LayoutTemplate>
                            <table style="width: 100%;" class="ms-listviewtable ms-rte-wpbox" cellpadding="0"
                                cellspacing="0">
                                <thead>
                                    <tr valign="top" class="ms-viewheadertr ms-vhltr">

                                        <th nowrap class="ms-vh2" style="font-weight: normal">
                                            Comment
                                        </th>
                                        <th nowrap class="ms-vh2" style="font-weight: normal">
                                            Status
                                        </th>
                                    </tr>
                                </thead>
                                <tr runat="server" id="ApprovedRow">
                                </tr>
                        </LayoutTemplate>
                        <AlternatingItemTemplate>
                            <tr class="ms-alternating ms-itmhover" runat="server" id="ApprovedRow">

                                <td class="ms-vb2">
                                    <%# Eval("Comment")%>
                                </td>
                                <td class="ms-vb2">
                                      <asp:DropDownList ID="ddlStatus" runat="server" Width="100px" AutoPostBack="true"  OnSelectedIndexChanged="ddlStatus_change">
                               <%--  <asp:ListItem Text="WIP" Value="0"></asp:ListItem>
                                  <asp:ListItem Text="Completed" Value="1"></asp:ListItem>--%>
                                </asp:DropDownList>

                                </td>
                            </tr>
                        </AlternatingItemTemplate>
                        <ItemTemplate>
                            <tr class="ms-itmhover" runat="server" id="ApprovedRow">

                                <td class="ms-vb2">
                                    <%# Eval("Comment")%>
                                </td>
                                <td class="ms-vb2">
                                      <asp:DropDownList ID="ddlStatus" runat="server" Width="100px" AutoPostBack="true"  OnSelectedIndexChanged="ddlStatus_change">
                                <%-- <asp:ListItem Text="WIP" Value="0"></asp:ListItem>
                                  <asp:ListItem Text="Completed" Value="1"></asp:ListItem>--%>
                                </asp:DropDownList>

                                </td>
                            </tr>
                        </ItemTemplate>
                        <EmptyDataTemplate>
                            <div class="ms-vb2">
                                No records found.
                            </div>
                        </EmptyDataTemplate>
                    </asp:ListView>
            </tr>
            <tr>
                <td>
                    <asp:DataPager ID="ReassessmentSelectorDataPager" runat="server" PagedControlID="ApprovedReassessmentsListView"
                        PageSize="100">
                        <Fields>
                            <asp:NumericPagerField ButtonType="Link" />
                        </Fields>
                    </asp:DataPager>
                </td>
            </tr>
        </table>
    </asp:PlaceHolder>
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Approved Reassessment Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    runat="server">
    Approved Reassessment Page
</asp:Content>

Dear Nico This is the new code for binding data

 protected void OnItemDataBound(object sender, ListViewItemEventArgs e)
    {
        List<string> listStatus = new List<string>(new string[] { "WIP", "Completed" });
        if (listStatus != null && listStatus.Count > 0)
        {
            string selectedStatus = string.Empty;
            var statList = listStatus.Select(item => new
            {
                Text = item,
                Value = item
            });

             selectedStatus = ddlStatus.SelectedValue;

            DropDownList DDLStatus = (e.Item.FindControl("ddlStatus") as DropDownList);

            if (string.IsNullOrEmpty(selectedStatus))
            {
                DDLStatus.DataSource = statList;
                DDLStatus.DataTextField = DATATEXTFIELD;
                DDLStatus.DataValueField = DATAVALUEFIELD;
                DDLStatus.DataBind();

                DDLStatus.Items.Insert(0, string.Empty);

            }
            else
            {
                DDLStatus.DataSource = statList;
                DDLStatus.DataTextField = DATATEXTFIELD;
                DDLStatus.DataValueField = DATAVALUEFIELD;
                DDLStatus.DataBind();

                DDLStatus.Items.Insert(0, selectedStatus);
            }               
        }
    }
2
  • how could it work with "autopostback = false" on the control properties?
    – Celophysis
    Aug 30, 2016 at 13:51
  • @Celophysis , I remove it and I put : ContentPlaceHolder content = Page.Master.FindControl("ApprovedReassessmentSelectorPlaceHolder") as ContentPlaceHolder; DropDownList ddltest = content.FindControl("ddlStatus") as DropDownList; still not working
    – BKChedlia
    Aug 30, 2016 at 13:57

1 Answer 1

0

With your code, you want to get you control directly from you Master, and only on the root level of the Master.Controls. You need to find your control with recursion.

Try with this methode:

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

And in your code behing of your page :

Control theDD = FindControlRecursive(Page.Controls, 'ddlStatus');
6
  • FindControlRecursive return null
    – BKChedlia
    Aug 30, 2016 at 19:46
  • Can you past your full code of your listView (or aspx page) ? and your code behnind too. When you try to get value of your dropdown on a add / update ?
    – Nico
    Aug 31, 2016 at 7:54
  • I edit my post with all code @Nico
    – BKChedlia
    Aug 31, 2016 at 8:12
  • OK, I see. This is a normal problem. you must understand the page life cycle. When you refrech you page (hit F5) you "restart" your page, so your dropdown will load with your default value. You must, first, save the selected value (in a variable/cach/session/properties bag....) and when you fill your drop down (in OnItemDataBound ) you must check if you have a selected value (in your variable, or cach or session ....) and fill your dropDown with ListItem and set Selected for the correct item.
    – Nico
    Aug 31, 2016 at 8:57
  • my new code is not working even when I select value, my variable is always empty
    – BKChedlia
    Aug 31, 2016 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.