【问题标题】:Populating a dropdownlist control and display "select one" as default填充下拉列表控件并默认显示“选择一个”
【发布时间】:2014-12-01 21:58:54
【问题描述】:

我有下面的代码块,如何将“选择一个”显示为顶部选定的值?

<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>

【问题讨论】:

  • 你有一个叫“select one”的学生,还是需要把它作为一个项目添加到列表顶部?

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


【解决方案1】:

您可以使用以下命令将其设为必需。您可以在 page_Load 事件中写入。

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

【讨论】:

  • 如果有一个名为“select one”的学生,这可能会起作用,但我希望没有。您还需要将您的行包含在if (!Page.IsPostBack) { ... } 中,否则该值将在任何时候触发回发时重置。
  • 是的,这可能是,正如 OP 所说,需要选择 "select one" 文本。
【解决方案2】:

您可以手动添加此默认项并将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>

【讨论】:

  • 是否需要Selected="True"
  • @Șhȇkhaṝ:是的,如果您希望它被选中(“作为顶部选定值”)。您也可以选择来自数据库的项目,但无论如何添加此静态项目。然后您必须使用SelectedIndexSelectedValueSelectedItem 或循环所有项目并以编程方式设置Selected 属性。
  • 我认为默认第一个元素默认被选中,第一个元素是select one?
  • @Șhȇkhaṝ:您似乎是对的,如果未选择任何项目,则默认选择第一个项目。但是你不想让它变得明确而不是总是看着MSDN吗?
  • 不只是想确认这一点:)
【解决方案3】:

使用列表项

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多