【问题标题】:set dropdownlist selection to hardcoded aspx defined value将下拉列表选择设置为硬编码的 aspx 定义值
【发布时间】:2013-11-27 01:08:12
【问题描述】:

如何将下拉选择设置为我在 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 页面中定义的上述索引 0

【问题讨论】:

    标签: c# asp.net html-select


    【解决方案1】:

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

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

    【讨论】:

    • 我不想将元素添加到我的表格中。否则我将不得不为我想要做同样的每一个表重复它。没有其他办法吗?
    • 您没有通过此答案将元素添加到数据表中。
    • 从后面的代码绑定下拉菜单,而不是提供 DataSourceId
    • 您将数据源绑定到代码隐藏中的下拉列表,通常是您的 mypage.aspx.cs 文件。您可以在 Page_Load 中执行此操作,或者在需要时创建自己的方法来执行此操作。只需确保将其放入 if(!IsPostBack) { myBindingMethod() } 中,除非您希望它在每次回发时刷新。
    • 这可能是检查如何从 codeproject.com/Questions/412998/… 后面的代码绑定下拉列表的良好起点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多