skip to Main Content

i’m trying to use a dropdownlist that has 2 values. Thé dropdownlist selected item should be set to yes or no , depending on a bool field that is in my object. I send my object through ViewData as well as the dropdownlist items (yes,no). I saw DropDownListFor in other answers but it is not accepted in the aspx code page. Can you help me please to know how to bind the DropDownList to the bool field of my object please? Thanks

I tried DropDownListFor but not being accepted in the aspx code page.

2

Answers


  1. Are you trying to bind your dropdownlist in the code behind file? If so, you can use:

    NameOfDropDownListControl.SelectedValue = NameOfBooleanObject
    
    Login or Signup to reply.
  2. Well, if your ddl has 2 values (yes, no), then you have to translate the bol vlaue into Yes, no, and then set the text of the ddl.

    So, say this drop down:

            <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem>Yes</asp:ListItem>
                <asp:ListItem>No</asp:ListItem>
            </asp:DropDownList>
    

    Then code to set to yes, or no?

    c#

            // testing code
    
            bool MyBolTest = false;
    
            DropDownList1.Text = MyBolTest ? "Yes" : "No";
    

    vb.net

        Dim MyBolTest As Boolean = True
    
        DropDownList1.Text = IIf(MyBolTest, "Yes", "No")
    

    So, you either assign the ddl selected index as 0 (first choice), 1 (2nd choice), or you can assign the "text" value of the ddl.

    Of course, the "context" of where/when you are doing this does suggest we may well need more details here.

    (such as is this a listview, grid view or whatever).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search