Search code examples
c#asp.netformview

How to bind the 'SelectedValue' in dropdown in ASP.NET Web Forms C# application from code behind?


I am attempting to use a dropdown list in the EditItemTemplate of a FormView. I am populating the dropdown from a datatable. The dropdown populates as expected, but when I try to save the changes the dropdown field is null. How can I save the selected value when making changes in the FormView?

Normally I would just put SelectedValue='<%# Bind("Surname") %>' in the dropdown markup, but apparently I can't since I'm populating it in the code behind.

Here's the dropdown markup:

<asp:DropDownList runat="server" ID="SurnameDdl" AppendDataBoundItems="True" ></asp:DropDownList>

Here's the datatable code I'm using to populate the dropdown:

private DataTable GetAdUsers()
{
    DataTable dt = new DataTable();

    dt.Columns.AddRange(new DataColumn[6]
    {
            new DataColumn("givenName", typeof (string)),
            new DataColumn("sn", typeof (string)),
            new DataColumn("mail", typeof (string)),
            new DataColumn("department", typeof (string)),
            new DataColumn("manager", typeof (string)),
            new DataColumn("DisplayField", System.Type.GetType("System.String"), "sn + ' ,' + givenName + ' ' + mail")
    });

    using (var context = new PrincipalContext(ContextType.Domain, null))
    {
        using (var group = (GroupPrincipal.FindByIdentity(context, "TWIA Underwriting"))) //Options include Users, Everybody, Agent Services, UnderwritingAdmin
        {
            var users = group.GetMembers(true);
            foreach (UserPrincipal user in users)
            {
                DirectoryEntry de = user.GetUnderlyingObject() as DirectoryEntry;
                dt.Rows.Add
                (
                    Convert.ToString(de.Properties["givenName"].Value),
                    Convert.ToString(de.Properties["sn"].Value),
                    Convert.ToString(de.Properties["mail"].Value),
                    Convert.ToString(de.Properties["department"].Value),
                    Regex.Replace((Convert.ToString(de.Properties["manager"].Value)), @"CN=([^,]*),.*$", "$1"),
                    de.Properties["DisplayField"].Value
                );
            }
        }
    }
    return dt;
}

Here's the OnDataBound event of the FormView:

protected void fvPhaudDets_OnDataBound(object sender, EventArgs e)
{
    if (fvPhaudDets.CurrentMode == FormViewMode.Edit)
    {
        DropDownList ddl = null;
        ddl = (DropDownList)fvPhaudDets.FindControl("SurnameDdl");
        ddl.DataSource = GetAdUsers();
        ddl.DataTextField = "DisplayField";
        ddl.DataValueField = "sn";
        ddl.DataBind();
        ddl.SelectedValue = "Surname";
    }
}

Do I need to add an event and code to the dropdown also? If so, what is needed?


Solution

  • You can use FindControl on the FormView to locate the DropDownList. It also works in the edit mode. If you have a FormView like this

    <asp:FormView ID="FormView1" runat="server">
        <EditItemTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem>Aa</asp:ListItem>
                <asp:ListItem>Bb</asp:ListItem>
                <asp:ListItem>Cc</asp:ListItem>
            </asp:DropDownList>
        </EditItemTemplate>
    </asp:FormView>
    
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    

    Then bind data to it and set the edit mode for testing

    if (IsPostBack == false)
    {   
        FormView1.DataSource = new string[1];
        FormView1.ChangeMode(FormViewMode.Edit);
        FormView1.DataBind();
    }
    

    You can now get the value on the button click

    protected void Button1_Click(object sender, EventArgs e)
    {
        DropDownList ddl = FormView1.FindControl("DropDownList1") as DropDownList;
        Label1.Text = ddl.SelectedValue;
    }