如何动态绑定下拉列表时禁用下拉列表项

时间:2015-07-19 09:21:35

标签: c# asp.net

下拉列表动态绑定为:

<asp:DropDownList ID="ddlSource" class="ddl" runat="server" DataSourceID="FROM1" DataTextField="CompanyName" DataValueField="CompanyName">
                </asp:DropDownList>
                <asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand="SELECT [CompanyName] FROM Company ORDER BY [CompanyName]"></asp:SqlDataSource>
                <br />

CompanyName表的值等于&#34;选择&#34;我希望此值显示在下拉列表中,但应该显示为灰色(禁用),以便用户无法选择或设置它。

任何想法如何在ASP.NET(而不是HTML)中做到这一点?

2 个答案:

答案 0 :(得分:0)

试试这个,但填充ddlSource将来自代码(它在vb.net中,对不起):

     Public Sub PopDDL()
        FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;"
        ddlSource.DataSourceID = "FORM1"
        ddlSource.DataTextField = "CompanyName"
        ddlSource.DataValueField = "CompanyName"
        ddlSource.DataBind()
        For Each itm As ListItem In ddlSource.Items
            If itm.Value = *your_condition* Then  'condition why this item must be disabled
                itm.Attributes.Add("disabled", "disabled")
            End If
        Next
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        PopDDL()
    End Sub

项目将显示但已禁用(灰色)。

更新: 我使用转换工具(vb.net到c#),我认为这是c#代码:

foreach (ListItem itm in ddlSource.Items) {
    if (itm.Value == *your_contidion*) { 'condition why this item must be disabled
        itm.Attributes.Add("disabled", "disabled");
    }
}

如果您使用itm.Enabled = False,则不会显示该项目。

UPDATE#2(通过在线转换器转换为c#代码):

aspx页面:

    <asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
   <asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>
   <br />
代码背后的代码:

public void PopDDL()
{
    FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;";
    ddlSource.DataSourceID = "FORM1";
    ddlSource.DataTextField = "CompanyName";
    ddlSource.DataValueField = "CompanyName";
    ddlSource.DataBind();
    foreach (ListItem itm in ddlSource.Items) {
        if (itm.Value == *your_condition*) {
            itm.Attributes.Add("disabled", "disabled");
        }
    }
}

protected void Page_Load(object sender, System.EventArgs e)
{
    PopDDL();
}

答案 1 :(得分:0)

基于评论中的其他问题,有完整的答案。

禁用:%s/this_one/that_one/g 并根据条件ListItems将其置于ddlSource的顶部:

aspx:

CompanyName="Select"
代码背后的代码:

<asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
<asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>
<br />