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()) {
}
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