为什么 DropDownList.SelectedIndexChanged 事件不触发?

发布于 2024-10-16 17:40:46 字数 3099 浏览 3 评论 0原文

我有一个绑定到 ObjectDataSource 的 DropDown。在其数据绑定事件中,我在 0 索引上添加“--select--”值。我在页面上有一个 LinkBut​​ton,在其客户端单击时,我在下拉列表中选择不同的项目(使用 JavaScript)。假设有 3 个项目,如 --select--、option1、option2 和 option3,现在在链接按钮的客户端上单击我选择的 option3,现在如果我选择默认值“--select--”,它不会触发 SelectedIndexChanged 事件。如果我选择任何其他值,它就会触发。为什么它对于默认值不起作用?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && !IsCallback)
    {
      this.FillDropDown("--Select--");
    }
    else
    {                            
        if (this.drp.SelectedItem != null)
            this.FillDropDown(this.drp.SelectedItem.Text);
        else
            this.FillDropDown("--Select--");
    }
}

protected void FillDropDown(string viewName)
{       
    this.obJectDataSource.Select();

    this.drp.Items.Clear();
    this.drp.SelectedIndex = -1;
    this.drp.DataBind();

    if (this.drp.Items.Count > 0)
    {           
        ListItem item = this.drp.Items.FindByText(viewName);
        if (item == null)
        {
            item = this.drp.Items.FindByText("--Select--");
        }
        if (item != null)
        {
            int selectedIndex = this.drp.Items.IndexOf(item);
            this.drp.Items[selectedIndex].Selected = true;
            this.drp.SelectedIndex = selectedIndex;                        
        }
    }
}

protected void drp_OnDataBound(object sender, EventArgs e)
{
    if (this.drp.Items.Count > 0)
    {               
        this.drp.Items.Insert(0, new ListItem("--Select--", "-1"));                
    }                        
}

protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{            
    if (drp.SelectedValue != "-1")
    {
        Session["SelectedItem"] = this.drp.SelectedItem.Text;

    }            
}
/// The button which do callback not postback

<dx:ASPxCallback ID="ASPxCallback1" runat="server" ClientInstanceName="Callback1" OnCallback="SaveFilter_Click">
    <ClientSideEvents CallbackComplete="function(s,e){Callback1Success(s,e);}" />
</dx:ASPxCallback>

<dx:ASPxButton ID="btn_Save" runat="server" CausesValidation="False" Height="20px" Text="Save" AutoPostBack="false" UseSubmitBehavior="false">
    <ClientSideEvents Click="function(s, e) {
            var isValid =  Validate(this, txt1.GetText());
            if(isValid==true) {
                Callback1.PerformCallback('Save');                               
            }  
            else {
                e.processOnServer = false;
            }}">
    </ClientSideEvents>
</dx:ASPxButton>

protected void SaveFilter_Click(object sender, CallbackEventArgs e)
{
    if (e.Parameter.ToString() == "Save")
    {
        if (!string.IsNullOrEmpty(txt_SaveSaveSearch.Text))
        {
            // saving data into data base.
            this.FillDropDown(txt.Text);                    
            e.Result = ASPxCallback.GetRenderResult(this.drp);
        }
    }
}

function Callback1Success(s,e) {
     var ctrl = document.getElementById('ctl00_ContentHolder_drp');
     ctrl.outerHTML = e.result;        
}

I have a DropDown which is bounded to an ObjectDataSource. On its data bound event, I am adding "--select--" value on the 0 index. I have a LinkButton on the page and on its client click, i am selecting different item on drop down (using JavaScript). Suppose there are 3 items like --select--, option1, option2 and option3 and now on link button's client click i selected option3, now if I select the default value "--select--", it does not fire the SelectedIndexChanged event. If I select any other value then it fires. Why does it not work for the default value?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && !IsCallback)
    {
      this.FillDropDown("--Select--");
    }
    else
    {                            
        if (this.drp.SelectedItem != null)
            this.FillDropDown(this.drp.SelectedItem.Text);
        else
            this.FillDropDown("--Select--");
    }
}

protected void FillDropDown(string viewName)
{       
    this.obJectDataSource.Select();

    this.drp.Items.Clear();
    this.drp.SelectedIndex = -1;
    this.drp.DataBind();

    if (this.drp.Items.Count > 0)
    {           
        ListItem item = this.drp.Items.FindByText(viewName);
        if (item == null)
        {
            item = this.drp.Items.FindByText("--Select--");
        }
        if (item != null)
        {
            int selectedIndex = this.drp.Items.IndexOf(item);
            this.drp.Items[selectedIndex].Selected = true;
            this.drp.SelectedIndex = selectedIndex;                        
        }
    }
}

protected void drp_OnDataBound(object sender, EventArgs e)
{
    if (this.drp.Items.Count > 0)
    {               
        this.drp.Items.Insert(0, new ListItem("--Select--", "-1"));                
    }                        
}

protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{            
    if (drp.SelectedValue != "-1")
    {
        Session["SelectedItem"] = this.drp.SelectedItem.Text;

    }            
}
/// The button which do callback not postback

<dx:ASPxCallback ID="ASPxCallback1" runat="server" ClientInstanceName="Callback1" OnCallback="SaveFilter_Click">
    <ClientSideEvents CallbackComplete="function(s,e){Callback1Success(s,e);}" />
</dx:ASPxCallback>

<dx:ASPxButton ID="btn_Save" runat="server" CausesValidation="False" Height="20px" Text="Save" AutoPostBack="false" UseSubmitBehavior="false">
    <ClientSideEvents Click="function(s, e) {
            var isValid =  Validate(this, txt1.GetText());
            if(isValid==true) {
                Callback1.PerformCallback('Save');                               
            }  
            else {
                e.processOnServer = false;
            }}">
    </ClientSideEvents>
</dx:ASPxButton>

protected void SaveFilter_Click(object sender, CallbackEventArgs e)
{
    if (e.Parameter.ToString() == "Save")
    {
        if (!string.IsNullOrEmpty(txt_SaveSaveSearch.Text))
        {
            // saving data into data base.
            this.FillDropDown(txt.Text);                    
            e.Result = ASPxCallback.GetRenderResult(this.drp);
        }
    }
}

function Callback1Success(s,e) {
     var ctrl = document.getElementById('ctl00_ContentHolder_drp');
     ctrl.outerHTML = e.result;        
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

并安 2024-10-23 17:40:47

更新:

基于修改后的问题 -

  1. 为什么不在下拉列表上设置 AppendDataBoundItems?该属性将允许下拉列表将项目附加到现有项目中。

    
    
        ;
    
  2. Page_Load 方法不执行您想要的操作。即使其中之一为 true,它的 else 部分也会被执行。例如:如果“Postback is true”或“callback is true”,它将进入 else 部分。但按照 (1) 步骤中的建议,设置 AppendDataBoundItems 并删除代码以添加“--select--”。


最可能的问题是 ViewState,设置 EnableViewState="true"

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" EnableViewState="true"%>

如果您使用 Maste Pages,则也必须启用它。

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" EnableViewState="true" ClassName="Site" %>

并在下拉菜单中控制 AutoPostback="true"

<asp:DropDownList ID='DropDownList1' runat='server' AutoPostBack='true' 
    OnSelectedIndexChanged='HandleOnDropDownListSelectedIndexChanged'>
</asp:DropDownList>

Update:

Based on the revised question -

  1. Why don't you set AppendDataBoundItems on the dropdownlist? The property would allow the dropdownlist to append items to the existing ones.

    <asp:DropDownList ID='DropDownList1' runat='server' AutoPostBack='true'  EnableViewState='true' AppendDataBoundItems='true'>
    
        <asp:ListItem Selected='True' Text='--Select--' Value='1'></asp:ListItem></asp:DropDownList>
    
  2. The Page_Load method doesn't do what you want to. The else part of it will be executed even if one of them is true ..ex: if "Postback is true" or "callback is true" it would go into the else part. But as suggested in the (1) step, set the AppendDataBoundItems and remove code to add "--select--".


Most likely issue be with ViewState, Set EnableViewState="true"

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" EnableViewState="true"%>

And if you are using Maste Pages you'll have to enable on it too.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" EnableViewState="true" ClassName="Site" %>

And in the dropdown web control AutoPostback="true"

<asp:DropDownList ID='DropDownList1' runat='server' AutoPostBack='true' 
    OnSelectedIndexChanged='HandleOnDropDownListSelectedIndexChanged'>
</asp:DropDownList>
≈。彩虹 2024-10-23 17:40:47

我不知道其他人是否有与我相同的问题,但碰巧我的值对于下拉列表中的每个项目都是相同的,并且在我更改值之前它永远不会触发事件。

I don't know if anyone else had the same Issue as I did but it just so happened that my values were the same for each item in the drop down list and it would never fire the event until I changed the values.

不一样的天空 2024-10-23 17:40:47

造成这种情况的另一个原因是,如果页面上有多个表单...我在页面上放置了第二个表单,但该表单还没有 ID 或操作。此表单干扰了包含我试图触发 onselectedindexchanged 处理程序的控件的表单...

我想如果所有其他方法都失败,请确保标记中只有一个表单。

Another cause of this is if you have more than one form on the page... I had placed a second form on the page that didn't have an ID or action yet. This form was interfering with the form that contained the control for which I was trying to fire the onselectedindexchanged handler...

I guess if all else fails, make sure you only have a SINGLE form in your markup.

樱娆 2024-10-23 17:40:47

我遇到了同样的问题,经过一段时间的挖掘,我发现设计器代码与我在 .aspx 中所做的更改不同步,其背后的代码仍然有一些对被删除的控件的引用导致对象引用不正确设置为对象错误的实例,但这发生在一些特殊情况处理中,这与实际问题无关(onselectionchanged 不触发)..

...但我也注意到 .aspx 中有一些 jscript 仍然包含我删除了旧的控件引用。编译器没有提示任何错误,因为这是仅在运行时捕获的 javascript。因此,我就我的案例得出结论,JavaScript 问题正在阻止自动回发事件。

I experienced the same issue, after a while digging in I found that the designer code is not in sync with the changes that I made in .aspx, the code behind which is still has some references to control that was deleted is causing object reference not set to instance of object error, but that's happening at some special case handling which is nothing to do with the actual issue (onselectionchanged not firing)..

... but I also noticed that there is some jscript in .aspx which is still contain the old references of control I deleted. The compiler didnt prompt any error as this is javascript which are caught only at runtime. Hence I concluded in my case that the javascript issue is preventing autopostback event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文