简体   繁体   中英

place controls conditionally on the web form

I have a listview and I am binding some questions to it so that users can answers them. Depending on the type of questions, it can be answered through different input controls like radiobuttonlist, dropdownlist , textbox , etc..

somewhat like this :

<itemtemplate>
    if (#eval("QuestionType") == 1)
       {
           <asp:RadioButtonList runat="Serer" />
       }
    elseif(#eval("QuestionType") == 2)
       {
           <asp:DropDownList runat="Serer" />
       }
    elseif(#eval("QuestionType") == 3)
       {
           <asp:CheckboxList runat="Serer" />
       }
</itemtemplate>

Above is the simplified example pseudo code of what I actually have.

I hope u understand what I am actually looking for.

You can't "place" them conditionally, but you can set their visibility conditionally.

<asp:RadioButtonList runat="server" 
    Visible='<%# (int)DataBinder.Eval(Container.DataItem("QuestionType")) == 1 %>' />

You need to add an event handler for the OnItemDataBound event for your ListView .

<asp:ListView ID="lstVw" runat="server" OnItemDataBound="lstVw_ItemDataBound">
    <ItemTemplate></ItemTemplate>
</asp:ListView>

From that point you can dynamically add controls to the Controls collection of the row's data item.

protected void lstVw_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        int val = int.Parse(e.Item.DataItem.ToString());

        switch (val)
        {
            case 1:
                RadioButtonList list = new RadioButtonList();
                list.Items.Add("Option 1");
                list.Items.Add("Option 2");

                e.Item.Controls.Add(list);

                break;
            case 2:
                //  Add a dropdown list
                break;
            case 3:
                //  Add a checkbox list
                break;
            default:
                //
                break;
        }
    }
}

One thing to note - I bound my ListView directly to a List<int> . So the code you'll need will be slightly different - have a look at this . The general idea is to cast e.Item.DataItem to whatever type the ListView is bound to and then get the value you need from that.

Now getting the values of the dynamically added controls on postback (assuming you need to) is going to be tricky. You'll have to loop through the controls on the page using Page.FindControl() or possibly even inspect the ListView and call FindControl on it's DataRows. You may need to use reflection to find each control's type. Like I said, it won't be straightforward, but you should be able to accomplish it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM