填充下拉列表控件并显示“选择一个”作为默认值

时间:2014-10-07 12:58:34

标签: asp.net vb.net drop-down-menu

我有下面的代码块,如何显示"选择一个"作为最高选择值?

<table>
    <tr>
        <td>
            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="StudentName" DataValueField="StudentName"></asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ddl_connStudentProfile %>" SelectCommand="SELECT [StudentName] FROM [StudentProfile]"></asp:SqlDataSource>
        </td>
    </tr>
</table>

3 个答案:

答案 0 :(得分:1)

使用列表项

<asp:ListItem Text="Select One" Value="-1"></asp:ListItem>

并使用此属性AppendDataBoundItems="true"

结合两者

<asp:DropDownList ID="DropDownList1" runat="server" 
     DataSourceID="SqlDataSource2" DataTextField="StudentName" 
     DataValueField="StudentName" AppendDataBoundItems="true">
    <asp:ListItem Text="Select One" Value="-1"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ddl_connStudentProfile %>" 
      SelectCommand="SELECT [StudentName] FROM [StudentProfile]">
</asp:SqlDataSource>

答案 1 :(得分:1)

您可以手动添加此默认项目,并将AppendDataBoundItems设置为true

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" 
        AppendDataBoundItems="True"
        DataTextField="StudentName" 
        DataValueField="StudentName">
    <asp:ListItem Selected="True" Value="0">select one</asp:ListItem>
</asp:DropDownList>

答案 2 :(得分:0)

您可以使用以下内容将所选内容设为必需。你可以在page_Load事件中写这个。

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("select one"));
}