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
移动此行NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product");
在绑定数据后的某个时间,发生的事情是您将其插入,然后绑定它的顶部。
The problem here is that you're using asp:SqlDataSource
. You need to query and bind your data from the code because you want to manipulate it.
Here is the sample logic.
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)
}
}
I'll let you try the different steps above, but let me know if you have any trouble.
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"));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.