Search code examples
c#asp.netdropdown

Populating a dropdown list with a stored procedure (showing usernames) then showing the users full name instead of username - slow


I have a drop down -

<asp:DropDownList ID="OriginatorDropDown" DataTextField="User"
DataValueField="User" runat="server" CssClass="form-control">
      <asp:ListItem Selected="True" Text="" Value="" />  </asp:DropDownList>

And I am populating it on the page load. However it is awfully slow.. i only have about 30 people in the list, it shouldnt be this slow. Any ideas please?

   protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
             GetUsers();
         }

     }


     private void GetUsers()
     {
         OriginatorDropDown.Items.Clear();
         OriginatorDropDown.DataSource = GetUserData();
         OriginatorDropDown.DataBind();

         foreach (ListItem ltItem in OriginatorDropDown.Items)
         {
             if (ltItem.Text != String.Empty)
             {
                 using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                 {
                     UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName
,ltItem.Text);
                     if (up != null)
                     {
                         ltItem.Text = up.DisplayName;
                     }

                 }
             }
         }
     }

     public DataSet GetUserData()
     {

         using (SqlConnection myConnection = new SqlConnection(ElectronicPayments))
         {
             //Get status descriptions
             using (SqlCommand cmd = new SqlCommand("GetAllUsers", myConnection))
             {
                 cmd.CommandType = CommandType.StoredProcedure;


                 SqlDataAdapter da = new SqlDataAdapter(cmd);
                 DataSet user = new DataSet();



                 myConnection.Open();
                 da.Fill(user);

                 return user;
             }
         }
     }

Solution

  • It is possible your context creation at each iteration may takes time. Could you try this :

        private void GetUsers()
         {
             OriginatorDropDown.Items.Clear();
             OriginatorDropDown.DataSource = GetUserData();
             OriginatorDropDown.DataBind();
    
    
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
             foreach (ListItem ltItem in OriginatorDropDown.Items)
             {
                 if (ltItem.Text != String.Empty)
                 {
    
    
                         UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName
    ,ltItem.Text);
                         if (up != null)
                         {
                             ltItem.Text = up.DisplayName;
                         }
    
    
                 }
             }
         }