【问题标题】:How do I fill my custom dropdownlist dynamically?如何动态填充我的自定义下拉列表?
【发布时间】:2014-02-17 14:01:50
【问题描述】:

这里我在asp:GridView 中有一个asp:DropDownList,以帮助用户将数据上传到SQL Server 2012

<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Site">
        <ItemTemplate>
            <asp:Label ID="lblSiteID" runat="server" Text='<%# Eval("SiteID")%>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:DropDownList ID="ddlSite" SelectedValue='<%# Bind("SiteID") %>' Text='<%# Bind("SiteID") %>' runat="server">
                    <asp:ListItem Value= "1" Text="Google" />
                    <asp:ListItem Value= "2" Text="Yahoo" />                        
            </asp:DropDownList>
        </EditItemTemplate>  
        <FooterTemplate>
            <asp:DropDownList ID="ddlSite" runat="server">
                <asp:ListItem>Google</asp:ListItem>
                <asp:ListItem>Yahoo</asp:ListItem>
            </asp:DropDownList>
        </FooterTemplate> 
        <ItemStyle Width="100px" />
    </asp:TemplateField>

SiteID 是数据库中的一个 int,这是它在代码隐藏中的定义方式:

private int numGoogle = 1;
private int numYahoo = 2;


//on insert and update
string SiteID = ((DropDownList)gvMainView.FooterRow.FindControl("ddlSite")).Text;
switch (SiteID)
{
    case "Inpatient Measures":
        SiteID = numGoogle.ToString();
        break;
    case "Outpatient Measures":
        SiteID = numYahoo.ToString();
        break;
}

//on Edit
switch (SiteID)
{
    string SiteID = ((DropDownList)gvMainView.FooterRow.FindControl("ddlSite")).SelectedValue;
    case "1":
        SiteID = "Google";
        break;
    case "2":
        SiteID = "Yahoo";
        break;
}

我的目标是让这个应用程序完全动态化,以便客户可以添加value 并将自己的文本发送到asp:dropdownlist。我已经在我的数据库中为此创建了一个表。我知道如何查询数据库以获取numSiteName 并将其用作valuetext。我需要知道一旦我拥有了asp:DropDownList,我该如何填写它们,这样变量就不会像现在这样被硬编码了。

【问题讨论】:

  • 如果我没记错的话,你只想从数据库中动态绑定下拉列表?

标签: c# asp.net asp.net-mvc indexing


【解决方案1】:

您设置下拉列表DataSource 属性,然后调用DataBind(); 将控件绑定到该数据。

确保提供DataValueFieldDataTextField,以便控件知道每个列表项的文本和值属性使用什么,例如:

ddlSite.DataSource = foo;
ddlSite.DataTextField = "FOO";
ddlSite.DataValueField = "foo_ID";

ddlSite.DataBind();

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 1970-01-01
    • 2023-04-03
    • 2020-06-26
    • 2015-12-11
    • 2019-06-06
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多