【问题标题】:How do I dynamically load a dropdownlist in a Webform Gridview?如何在 Webform Gridview 中动态加载下拉列表?
【发布时间】:2023-03-15 16:20:01
【问题描述】:

我有一个模板化的 Gridview,我只想显示一列(问题 --- 这些是数据库获得的),另一列是可能答案的下拉列表(选项)。下拉列表的值会根据问题的类型而变化。只有 2 种类型:T/F 或远程(Lo、Med、High)。所以如果问题是类型 1,下拉列表应该只显示 T/F。同样,如果它是 II 型。

下面显示的是gridview和加载下拉列表的方法(据说):

    <asp:GridView AutoGenerateColumns="false" runat="server" ID="SurveyView">
    <Columns>

        <asp:BoundField HeaderText="Questionnaire" DataField="Questionaire" ReadOnly="true"/>
        <asp:BoundField HeaderText="QuestionID" DataField="Id" ReadOnly="true" Visible="false" />
        <asp:BoundField HeaderText="IsBoolean" DataField="Filter" ReadOnly="true" Visible="false" />
        <asp:TemplateField HeaderText="Response">
            <ItemTemplate>
                <asp:DropDownList ID="UserDropDown" runat="server" AppendDataBoundItems="true" DataSource="LoadDropdownList(Filter)" DataTextField="key" DataValueField="value"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


        public Dictionary<String, String> GenerateDropdownList(bool BooleanFilterStatus)
    {
        Dictionary<String, String> tempStores = new Dictionary<string, string>() ; 
        if (BooleanFilterStatus)
        {
            tempStores.Add(Boolean.TrueString, Boolean.TrueString);
            tempStores.Add(Boolean.FalseString, Boolean.FalseString);
        }
        else
        {
            tempStores.Add("NONE", "NIL");
            tempStores.Add("Lo", "Low");
            tempStores.Add("Medium", "Medium");
            tempStores.Add("High", "High"); 
        }

        return tempStores; 
    }

我希望通过使用 LoadDropdownList() 来填充列表。但这似乎不起作用。

任何想法或其他可能的解决方案将不胜感激。

【问题讨论】:

    标签: asp.net gridview drop-down-menu datasource


    【解决方案1】:

    这样的事情怎么样

    <asp:DropDownList ID="UserDropDown" runat="server" AppendDataBoundItems="true" 
     ondatabinding="DropDownList1_DataBinding" DataTextField="key" DataValueField="value"></asp:DropDownList>
    

    在代码隐藏中

     protected void DropDownList1_DataBinding(object sender, EventArgs e)
        {
            var ddl = sender as DropDownList;
            if(ddl!=null)
            {
              //populate list. 
              ddl.Items.Add(new ListItem("test"));
            }
        }
    

    【讨论】:

    • 酷。谢谢你的建议,我会试试的。
    • 但是如何将最初选择的值设置为网格行中的某个值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多