如何将另一个项添加到数据绑定DropDownList?

时间:2014-07-25 22:27:37

标签: c# asp.net

我的ASP.NET C#Web应用程序中有一个DropDownList控件,从SqlDataSource读取。我有一个显示的项目列表,但我想在第一个项目中添加更多文字,并使用value == 0说“请选择部门”。

这是我的代码:

<asp:DropDownList
   ID="DropDownList1"
   DataSourceID="sdsdepartment"
   runat="server"
   DataTextField="department_name"
   DataValueField="deptid"
></asp:DropDownList>
<asp:SqlDataSource
   ID="sdsdepartment"
   runat="server"
   ConnectionString="<%$ ConnectionStrings:blabla %>"
   SelectCommand="SELECT [department_name], [deptid] FROM [DEPARTMENT]"
></asp:SqlDataSource>

3 个答案:

答案 0 :(得分:2)

您可以将SelectCommand更改为:

SELECT 'Please select department' as [department_name], 0 as [deptid]
UNION
SELECT [department_name], [deptid] FROM [DEPARTMENT]

答案 1 :(得分:0)

在Page_Load中添加以下行

DropDownList1.Items.Insert(0,new ListItem(&#34;请选择部门&#34;,&#34; 0&#34;));

答案 2 :(得分:0)

这将非常简单

<asp:DropDownList
ID="DropDownList1"
DataSourceID="sdsdepartment"
runat="server"
DataTextField="department_name"
DataValueField="deptid"
AppendDataBoundItems="True" // set this property to True
>
<asp:ListItem Text="select Department" Value="0"></asp:ListItem> //here add one default item

</asp:DropDownList>
<asp:SqlDataSource
ID="sdsdepartment"
runat="server"
ConnectionString="<%$ ConnectionStrings:blabla %>"SelectCommand="SELECT [department_name], 
[deptid] FROM [DEPARTMENT]"
></asp:SqlDataSource>