You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GridView编辑模式下设置DropDownList选中值并解决rowView为null问题

问题根因

编辑模式下e.Row.DataItem为null,是因为DataItem仅在GridView执行数据绑定的生命周期阶段有效,触发编辑操作的回发过程中如果没有重新绑定数据源,DataItem会自动释放为null。

解决方案

方案1:使用DataKey存储字段值(更稳定,推荐)

不需要依赖DataItem,通过GridView的DataKey集合获取对应行的Status值即可,步骤如下:

  1. 给GridView控件添加DataKeyNames属性,将Status字段加入其中(如果已有主键字段,直接追加即可):
<asp:GridView ID="grdPresenters" runat="server" DataKeyNames="YourPrimaryKey,Status" ......>
  1. 修改grdPresenters_RowDataBound中获取Status的代码,替换原来的DataRowView相关逻辑:
// 删掉原来的DataRowView转换代码
string status = grdPresenters.DataKeys[e.Row.RowIndex]["Status"].ToString();
// 先判断值是否存在,避免抛出异常
if(ddList.Items.FindByValue(status) != null)
{
    ddList.SelectedValue = status;
}

方案2:修正数据绑定逻辑,保留DataItem取值

如果要继续使用e.Row.DataItem取值,需要保证编辑操作触发后正确执行了GridView的绑定逻辑:

  1. 确保Page_Load中的GridView绑定逻辑加了回发判断:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        // 你的GridView绑定方法,比如BindGrid()
        BindGrid();
    }
}
  1. 在GridView的RowEditing事件中,设置编辑索引后立即重新绑定数据源:
protected void grdPresenters_RowEditing(object sender, GridViewEditEventArgs e)
{
    grdPresenters.EditIndex = e.NewEditIndex;
    BindGrid();
}

优化建议

当前DropDownList的选项是固定枚举值,不需要每次行绑定时动态创建DataTable绑定,可以直接在前端硬编码选项,减少冗余代码:

<asp:DropDownList runat="server" ID="ddStatusList" AppendDataBoundItems="True" CssClass="form-control">
    <asp:ListItem Text="Pending" Value="Pending" />
    <asp:ListItem Text="Approved" Value="Approved" />
    <asp:ListItem Text="Rejected" Value="Rejected" />
</asp:DropDownList>

修改后可以删除RowDataBound中创建DataTable绑定DropDownList的相关代码。

内容的提问来源于stack exchange,提问作者Bryan Dellinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:57:03