c# - 无法在 ASP C# 中切换到 DropDownList 中的另一个值(它切换回以前的值)

标签 c# asp.net

我定义了 DDL 的 aspx 文件:

<asp:DropDownList ID="myDDL" runat="server"
     OnSelectedIndexChanged="myDdlChange" 
     AutoPostBack="true"  EnableViewState="true" />

我的代码隐藏文件

protected void PopulateControl()
{
    //populate my DDL based on an array (OK)
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    PopulateControl();
}

protected override void OnLoad(EventArgs e)
{
            base.OnLoad(e);
            ...
            this.DataBind();
}
protected void myDdlChange(object source, EventArgs e)
{
    Session["myDDL"] = myDDL.SelectedValue;
    myTextBox.Text = MyMethod(myDDL.SelectedValue);
}

myTextBox 是一个文本框,每次 DDL 更改时都会根据将所选值作为参数的方法进行填充。

DDL 还需要添加什么来保留用户选择的值。 现在,当我切换到 DDL 中的另一个值时,我选择的值将切换回数组的第一个元素。

另外,当我调试并切换到 DDL 中的另一个值时,为什么 myDdlChange 方法没有获得焦点? (我在这个方法中有一个断点)

最佳答案

因为每次你这样做:

PopulateControl();

您删除 DropDownList 中的所有值并重新添加它们。因此,删除了用户选择的任何内容,并添加了一个新的(未选择的)值列表。每次加载页面时都会发生这种情况,这发生在 myDdlChange 处理程序之前。

您可以防止它在回发时重新填充列表:

if (!IsPostBack)
    PopulateControl();

这样,DropDownList 只会在初始页面加载时填充,而不会在后续的回发页面加载时填充。

Also, why doesn't myDdlChange method take focus when I debug and switch to another value in the DDL?

当你切换到另一个值时,你是否回发到服务器?如果不是,则没有任何内容调用服务器端代码。如果您正在回发到服务器,您是否已将此事件注册到控件中?设计器通常会为您完成此操作,但如果您手动创建它,则您还需要手动将其注册到控件。

关于c# - 无法在 ASP C# 中切换到 DropDownList 中的另一个值(它切换回以前的值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38720957/

相关文章:

javascript - Asp.net 2.0网页_播放文件mp3、mp4

c# - WCF Rest api - [WebGet] 工作,但未找到 [WebInvoke(...GET...)] 的端点

c# - 为什么 Point.Offset() 没有在只读结构中给出编译器错误?

c# - ExceptionAggregator.cs 在哪里

c# - 在 Web 项目的每个页面中识别标签和按钮控件

asp.net - 如何安全地引用 https 页面上的 http 资源?

c# - Button.PerformClick() 不等待异步事件处理程序

c# - 为什么 Application.Restart() 不可靠?

asp.net - Web.config 中的瑞典语文本

c# - MVC4 - 表单不显示新模型值