我有一个下拉列表并使用SQL数据源来检索SQL服务器中的产品名称。现在,我想添加"请选择一个产品"下拉列表的选项。 据我所知,我使用
添加选项到下拉列表 <asp:ListItem Selected ="true" Value = "1">1</asp:ListItem>
因为,我没有添加值但是从DB中检索值,如何另外实现此选项并将其作为第一个位置添加到我的下拉列表中?
我尝试了以下代码,但无法在第一个位置获得。另外,每次我得到额外的&#34;请选择&#34;每当我选择其他值时选项。
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>
我还将自动发布回设为true.Thanks提前
答案 0 :(得分:0)
在绑定数据后,将此行NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product");
移动到其他地方,发生的事情就是插入此内容,然后将其绑定到顶部。
答案 1 :(得分:0)
此处的问题是您正在使用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)
}
}
我允许您尝试上述不同的步骤,但如果您遇到任何问题请与我联系。
答案 2 :(得分:0)
感谢您的回复。我找出了实际问题并且能够在简单的步骤中完成它。 首先,我将下拉列表中的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"));
}
}