2014-10-07 44 views
0

我有下面的代码块,如何显示“选择一个”作为顶部选定的值?填充下拉列表控件并显示“选择一个”作为默认

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

您是否有名为“select one”的学生,或者您是否需要将其添加为列表顶部的项目? – 2014-10-07 13:04:13

回答

0

您可以使用以下内容使所需的选择。你可以在page_Load事件中写这个。

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

如果有一个叫“选择一个”的学生,这可以工作,但我希望没有。您还需要将行包装在'if(!Page.IsPostBack){...}'中,否则只要触发回发,该值就会重置。 – 2014-10-07 13:03:54

+0

是的,这可能是,因为OP说,“选择一个”文本需要被选中。 – 2014-10-07 13:04:58

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

您可以手动添加此默认项,并设置AppendDataBoundItemstrue

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

是否需要'Selected =“True”'? – 2014-10-07 13:08:59

+0

@Şhȇkhaṝ:是的,如果你想要它被选中(_“作为最高选择值”)。您也可以选择来自数据库的项目,但无论如何都要添加此静态项目。然后你必须使用'SelectedIndex','SelectedValue'或'SelectedItem'或循环所有的项目并以编程方式设置'Selected'属性。 – 2014-10-07 13:09:45

+0

我想默认第一个元素默认被选中,第一个元素是'select one'? – 2014-10-07 13:13:32

相关问题