将dropdownlist选择设置为硬编码的aspx定义值

时间:2013-11-26 16:59:02

标签: c# asp.net html-select

如何将下拉选项设置为在aspx页面中硬编码的选项? “

我这样定义:

 <asp:DropDownList ID="DropDownListTug" runat="server" 
  DataSourceID="SqlDataSourceTugs"
  DataTextField="Tug_Name" DataValueField="Tug_ID" AutoPostBack="True"         
  AppendDataBoundItems="True"OnSelectedIndexChanged="ShowNewRateBtn">
 <asp:ListItem Value="0" Text="&lt;Select&gt;" Enabled="True" Selected="False"></asp:ListItem>
</asp:DropDownList>

我正在尝试使用

重置代码隐藏
       protected void NewTug_Click(object sender, EventArgs e)
    {
        processTugs.Visible = true;
        tname.Visible = true;
        allButtons.Visible = true;

        pubvar.EnableAllControls(Page);
        //DropDownListTug.ClearSelection();
        //DropDownListTug.SelectedIndex = 0;
        //DropDownListTug.SelectedValue = "0";
        BtnNewRate.Visible = false;
        BtnDelete.Visible = false;
        BtnUpdate.Visible = false;
        BtnSave.Visible = false;
        BtnNewTugSave.Visible = true;
        BtnCancel.Visible = true;

    }

但它导致它选择表的第一个索引,而不是我在aspx页面中定义的上述索引

1 个答案:

答案 0 :(得分:1)

添加数据源并绑定下拉列表将删除现有元素。在绑定后的代码中,在索引零处通过Insert添加元素。

DropDownListTug.DataSource = datatable;
DropDownListTug.DataBind(); 
DropDownListTug.Items.Insert(0, new ListItem("Add New", ""));
DropDownListTug.ClearSelection();
DropDownListTug.SelectedIndex = 0;