我遇到了同样的问题,但是这个修复(Jason's,将条件添加到处理程序)对我不起作用;编辑行从未被数据绑定,因此该条件从未评估为真。RowDataBound 根本不会使用与 GridView.EditIndex 相同的 RowIndex 调用。不过,我的设置有点不同,因为我没有以编程方式绑定下拉列表,而是将其绑定到页面上的 ObjectDataSource。但是,下拉列表仍然必须每行单独绑定,因为它的可能值取决于行中的其他信息。所以 ObjectDataSource 有一个 SessionParameter,我确保在需要绑定时设置适当的会话变量。
<asp:ObjectDataSource ID="objInfo" runat="server" SelectMethod="GetData" TypeName="MyTypeName">
<SelectParameters>
<asp:SessionParameter Name="MyID" SessionField="MID" Type="Int32" />
</SelectParameters>
以及相关行中的下拉菜单:
<asp:TemplateField HeaderText="My Info" SortExpression="MyInfo">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditMyInfo" runat="server" DataSourceID="objInfo" DataTextField="MyInfo" DataValueField="MyInfoID" SelectedValue='<%#Bind("ID") %>' />
</EditItemTemplate>
<ItemTemplate>
<span><%#Eval("MyInfo") %></span>
</ItemTemplate>
</asp:TemplateField>
我最终做的不是在 GridView 中使用 CommandField 来生成我的编辑、删除、更新和取消按钮;我使用 TemplateField 自行完成,通过适当设置 CommandNames,我能够触发 GridView 上的内置编辑/删除/更新/取消操作。对于 Edit 按钮,我将 CommandArgument 设置为绑定下拉列表所需的信息,而不是像通常那样使用行的 PK。幸运的是,这并没有阻止 GridView 编辑相应的行。
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" ImageUrl="~/images/delete.gif" AlternateText="Delete" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Delete" />
<asp:ImageButton ID="ibtnEdit" runat="server" ImageUrl="~/images/edit.gif" AlternateText="Edit" CommandArgument='<%#Eval("MyID") %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibtnUpdate" runat="server" ImageUrl="~/images/update.gif" AlternateText="Update" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Update" />
<asp:ImageButton ID="ibtnCancel" runat="server" ImageUrl="~/images/cancel.gif" AlternateText="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
在 RowCommand 处理程序中:
void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
Session["MID"] = Int32.Parse(e.CommandArgument.ToString());
}
当然,RowCommand 发生在行进入编辑模式之前,因此在下拉数据绑定之前发生。所以一切正常。这有点像黑客,但我花了足够的时间试图弄清楚为什么编辑行还没有被数据绑定。