GridView中e.Row.Cells[X].Text始终为空的问题排查求助
GridView行删除时单元格Text为空的排查方案
先确认行类型是否正确
在RowDataBound事件中,必须先判断当前行是数据行,否则会取到Header/Footer行的空单元格:if (e.Row.RowType == DataControlRowType.DataRow) { // 仅处理数据行逻辑 }检查单元格是否包含服务器控件
如果单元格内用了Label、TextBox这类控件,直接取Cells[x].Text会返回空,需通过FindControl获取控件的Text属性:Label targetLabel = e.Row.Cells[2].FindControl("lblTarget") as Label; if (targetLabel != null) { string cellValue = targetLabel.Text; // 用该值设置删除确认提示 }改用DataKeyNames存储关键值
若单元格设置了Visible="false",或不想在页面显示关键值,可在GridView的DataKeyNames中指定字段,通过索引取值:<!-- 前台配置DataKeyNames --> <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID,TargetValue">...</asp:GridView>// 后台获取对应值 string targetValue = GridView1.DataKeys[e.Row.DataItemIndex]["TargetValue"].ToString();验证数据绑定是否正确
若使用TemplateField自定义单元格,确保控件已正确绑定数据:<asp:TemplateField HeaderText="目标值"> <ItemTemplate> <asp:Label ID="lblTarget" runat="server" Text='<%# Eval("TargetValue") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>
内容的提问来源于stack exchange,提问作者Ram
相关产品推荐
相关产品推荐

