C# asp.net asp:DropDownList onSelectedIndexChanged 未在数据绑定 asp:GridView 中触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13445390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:34:36  来源:igfitidea点击:

asp.net asp:DropDownList onSelectedIndexChanged not firing in databound asp:GridView

c#asp.neteventsgridviewdatabound

提问by DerpyNerd

I'm having troubles with this and I can't figure it out. I have a databound asp:gridview (sqldatasource) with an asp:dropdownlist inside an itemtemplate. The dropdownlist has an onSelectedIndexChanged event listener but it doesn't fire.

我遇到了这个问题,我无法弄清楚。我有一个数据绑定的 asp:gridview (sqldatasource),在 itemtemplate 中有一个 asp:dropdownlist。下拉列表有一个 onSelectedIndexChanged 事件侦听器,但它不会触发。

Here's the markup:

这是标记:

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
    <ContentTemplate>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        EmptyDataText="There are no data records to display." EnableViewState="True" >
        <Columns>
            <asp:TemplateField HeaderText="Delete user">
                <ItemTemplate>
                    <asp:Button runat="server" ID="btnDelete" CommandName="Delete" CommandArgument='<%# Eval("UserId") %>'
                        Text="Delete" OnCommand="DeleteUser" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Block users">
                <ItemTemplate>
                    <asp:Button runat="server" ID="btnBlock" CommandName="Block" CommandArgument='<%# Eval("UserId") %>'
                        Text="Block" OnClick="btnBlock_Click" Visible='<%# !Convert.ToBoolean(Eval("IsLockedOut")) %>' />
                    <asp:Button runat="server" ID="btnDeblock" CommandName="Deblock" CommandArgument='<%# Eval("UserId") %>'
                        Text="Deblock" OnClick="btnBlock_Click" Visible='<%# Convert.ToBoolean(Eval("IsLockedOut")) %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Change role">
                <ItemTemplate>
                    <asp:DropDownList ID="ChangeRole" runat="server" EnableViewState="false"
                        OnSelectedIndexChanged="ChangeRole_SelectedIndexChanged" AutoPostBack="true"
                        ToolTip='<%# Bind("UserName") %>' >
                        <asp:ListItem Text="Choose a role" Value="" Selected="True" />
                        <asp:ListItem Text="Admin" Value="" />
                        <asp:ListItem Text="Member" Value="" />
                        <asp:ListItem Text="Visitor" Value="" />
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="RoleName" HeaderText="Current role" ReadOnly="true" SortExpression="RoleName" />
            <asp:BoundField DataField="UserName" HeaderText="Username" ReadOnly="True" SortExpression="UserName" />
            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
            <asp:BoundField DataField="LastLoginDate" HeaderText="Last login" 
                SortExpression="LastLoginDate" />
            <asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked" 
                SortExpression="IsLockedOut" />
            <asp:BoundField DataField="FailedPasswordAttemptCount" 
                HeaderText="Failed logins" 
                SortExpression="FailedPasswordAttemptCount" />
            <asp:BoundField DataField="Comment" HeaderText="Comments" 
                SortExpression="Comment" />
        </Columns>
    </asp:GridView>
    <asp:Label ID="lblSuccess" runat="server" Text="Database updated successfully." Visible="false" meta:resourcekey="success" />
    <asp:Label ID="lblError" runat="server" Text="An error occured, database was not updated." />
    </ContentTemplate>
</asp:UpdatePanel>

I've added the updatepanel code because I figured it might be relevant. In the code behind, I made sure to bind the gridview only if !Page.IsPostBack

我已经添加了 updatepanel 代码,因为我认为它可能是相关的。在后面的代码中,我确保仅当 !Page.IsPostBack 时才绑定 gridview

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        GridView1.DataSourceID = "SqlDataSource1";
        GridView1.DataKeyNames = new String[] {"UserId"};
        GridView1.DataBind();
    }
}

Then I made an actionlistener for the dropdownlist

然后我为下拉列表制作了一个动作监听器

protected void ChangeRole_SelectedIndexChanged(object sender, EventArgs e)
{
    Logger.Info("it's alive!", "Chaning role");
}

I already tried enableViewState="True || False" (for both gridview and dropdownlist) and autoPostBack="True || False" in both directions but the logfile doesn't show the "It's alive" message. The event hasn't been triggered on changing index.

我已经在两个方向上尝试过 enableViewState="True || False"(对于 gridview 和 dropdownlist)和 autoPostBack="True || False",但日志文件没有显示“It's alive”消息。更改索引时未触发该事件。

Any ideas?

有任何想法吗?

采纳答案by DerpyNerd

Alright,

好吧,

I've finally found the solution. Searching the internet reveals this is not an uncommon problem. The solution however, is never too far away.

我终于找到了解决方案。搜索互联网发现这不是一个罕见的问题。然而,解决方案永远不会太远。

First I changed everything on my page (including page directive, gridview, updatetemplate and dropdownlist) to EnableViewState="true", Then I set the AutoPostBack="true" on my dropdownlist, Finally, I need to make sure that I'm not binding the gridview with it's data in the page_load method because this phase in the lifecycle already rebinds the dropdownlists and sets their selectedindex back to default before the onselectedindexchanged event can be fired.

首先,我将页面上的所有内容(包括页面指令、gridview、updatetemplate 和 dropdownlist)更改为 EnableViewState="true",然后在下拉列表中设置 AutoPostBack="true",最后,我需要确保我不是在 page_load 方法中将 gridview 与其数据绑定,因为生命周期中的这个阶段已经重新绑定下拉列表并将它们的 selectedindex 设置回默认值,然后才能触发 onselectedindexchanged 事件。

I just let the gridview do the binding as usual by setting it's datasourceid. During my search, I've seen many people with a similar issue and I think this should fix a lot of them. Or at least it's worth a shot :)

我只是让 gridview 像往常一样通过设置它的 datasourceid 来进行绑定。在我的搜索过程中,我看到很多人有类似的问题,我认为这应该可以解决很多问题。或者至少值得一试:)

回答by Aram Beginyan

Try change GridView like this

尝试像这样更改 GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="There are no data records to display." EnableViewState="True" DataSource="SqlDataSource1" DataKeyNames="UserId" >

clear the Page_Load function

清除 Page_Load 函数

protected void Page_Load(object sender, EventArgs e)
{
}

回答by Mark Vickery

have you tried changing the view state of the DropDownList to "true":

您是否尝试将 DropDownList 的视图状态更改为“true”:

<asp:DropDownList ID="ChangeRole" runat="server" EnableViewState="true" OnSelectedIndexChanged="ChangeRole_SelectedIndexChanged" AutoPostBack="true" ...

<asp:DropDownList ID="ChangeRole" runat="server" EnableViewState="true" OnSelectedIndexChanged="ChangeRole_SelectedIndexChanged" AutoPostBack="true" ...

if the state of the drop down is being forgotten between postbacks then the index wont have changed, hence the SelectedIndexChange event not firing.

如果在回发之间忘记了下拉菜单的状态,则索引不会改变,因此 SelectedIndexChange 事件不会触发。

回答by writeToBhuwan

Set the AutoPostBack="true"for the DropDownList.

AutoPostBack="true"为 DropDownList设置。

and set the updatemode of update panel to always like this

并将更新面板的更新模式设置为总是这样

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Always">

Or set a trigger which handles the SelectedIndexChanged event of the DropDownList.

或者设置一个触发器来处理 DropDownList 的 SelectedIndexChanged 事件。

回答by Cammy

Like you said its not an uncommon problem. I had the same problem myself, therefore I'd like to contribute with a check list to rule out some more common problems:

就像你说的,这不是一个罕见的问题。我自己也遇到了同样的问题,因此我想提供一个检查清单来排除一些更常见的问题:

  • Make sure ViewState is activated, EnableViewState="True"
  • If above point doesn't work also check if any parent element has ViewState disabled
  • Activate post back AutoPostBack="True"
  • Make sure your dababining takes place onlyif its not a postback if(!Page.IsPostBack), ViewState will save the chosen option and for your form (if you have one)
  • 确保 ViewState 已激活, EnableViewState="True"
  • 如果上述点不起作用,还要检查是否有任何父元素禁用了 ViewState
  • 激活回帖 AutoPostBack="True"
  • 确保您的 dababining在它不是回发时才发生if(!Page.IsPostBack),ViewState 将保存所选选项和您的表单(如果您有)

That's all I could think of for now :) hope it helps anyone!

这就是我现在能想到的:) 希望它可以帮助任何人!

回答by Binary Thoughts

Though this is an old article I hope it still contributes.

虽然这是一篇旧文章,但我希望它仍然有所贡献。

I had the same problem, for me the solution was to set values for the "Value" property of a ListItems. So change the code as follows:

我遇到了同样的问题,对我来说,解决方案是为 ListItems 的“Value”属性设置值。所以把代码改成如下:

<asp:DropDownList ID="ChangeRole" runat="server" EnableViewState="false" 
OnSelectedIndexChanged="ChangeRole_SelectedIndexChanged" AutoPostBack="true"                       ToolTip='<%# Bind("UserName") %>' >
<asp:ListItem Text="Choose a role" Value="0" Selected="True" />
<asp:ListItem Text="Admin" Value="1" />
<asp:ListItem Text="Member" Value="2" />
<asp:ListItem Text="Visitor" Value="3" />
</asp:DropDownList>

Hope this will help someone.

希望这会帮助某人。

回答by Serb

This solved my problem: CausesValidation="False"Hereare the details.

这解决了我的问题:CausesValidation="False"是详细信息。