添加 "Please Select" 到从数据库检索值的下拉列表

Add "Please Select" to Drop-down list that retrieves values from Data base

我有一个下拉列表并使用 SQL 数据源,我从 SQL 服务器检索产品名称。现在,我想在下拉列表中添加 "Please Select a product" 选项。 据我所知,我使用

向下拉列表添加选项
 <asp:ListItem Selected ="true" Value = "1">1</asp:ListItem>

因为我不是添加值而是从数据库中检索值,如何另外实现此选项并将其添加到我的下拉列表的第一个位置?

我尝试了下面的代码,但一开始无法获取 position.Also,每次我选择其他值时都会获得额外的 "please select" 选项。

protected void NameDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
 NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product");
 SqlCommand cmd = new SqlCommand("SELECT ProductID, Price, Description, Rating FROM Product_Info Where Name = '" + NameDropDownList.Text + "'", conn);
 SqlDataReader myReader;
 conn.Open();
 myReader = cmd.ExecuteReader();
 while (myReader.Read()) {
 //Logic
}
  conn.Close();
  myReader.Close();

这是我绑定数据的代码:

 <tr>
     <td class="style2">Name</td>
      <td>
            <asp:DropDownList ID="NameDropDownList" runat="server" Height="16px" 
                Width="130px" AutoPostBack="True" DataSourceID="NameSqlDataSource" 
                DataTextField="Name" DataValueField="Name" 
                onselectedindexchanged="NameDropDownList_SelectedIndexChanged">    
            </asp:DropDownList>

            <asp:SqlDataSource ID="NameSqlDataSource" runat="server" 
                ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>" 
                SelectCommand="SELECT [Name] FROM [Product_Info]"></asp:SqlDataSource>
        </td>
</tr>

我也提前开启了自动post回true.Thanks

将此行 NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product"); 移动到绑定数据后的某个位置,发生的事情是插入它,然后绑定到它的顶部。

这里的问题是您正在使用 asp:SqlDataSource。您需要从代码中查询和绑定您的数据,因为您想要对其进行操作。

这是示例逻辑。

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // 1- Query into a list
        // 2- Add your custom item at the 1st position
        // 3- Set the DataSource of your list
        // 4- Make sure you bind your fields (text and value)
    }
}

我会让你尝试上面的不同步骤,但如果你有任何问题,请告诉我。

感谢您的回复。我弄清楚了实际问题并能够通过简单的步骤完成。 首先,我将下拉列表的 AppendDataBoundItems 行为设置为 TRUE 并保留以下代码并且它完美运行。

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        { 
           NameDropDownList.Items.Insert(0, new ListItem("Please Select a Product", "Please Select a Product"));
        }

   }