Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a drop-down list and uses the SQL data source for it where I am retrieving the product names from SQL server. Now, I want to add "Please Select a product" Option to the drop-down list. As far as my knowledge, I add options to drop-down list by using

 <asp:ListItem Selected ="true" Value = "1">1</asp:ListItem>

Since, I am not adding the values but retrieving the values from DB, how to achieve this Option additionally and add to it as first position to my drop-down list?

I tried the below code, but not able to do get at first position.Also, each time I am getting extra "please select" option whenever I am selecting other values.

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();

Here is my code behind where I bind the data:

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

I also enables the Auto post back to true.Thanks in advance

like image 774
Phanindra Avatar asked Jan 23 '26 21:01

Phanindra


1 Answers

Thanks for your responses. I figured out the actual problem and able to done it in simple step. First, I make the AppendDataBoundItems behavior of my drop-down list To TRUE and kept the following code and it works perfectly.

 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"));
        }

   }
like image 127
Phanindra Avatar answered Jan 26 '26 12:01

Phanindra