ASP.NET GridView无法获取上一行单元格值,格式设置失效求助
ASP.NET GridView行格式设置问题:无法获取单元格文本值
嘿,我看你在给GridView设置行格式的时候遇到了麻烦——想让某列值和上一行不同时改变背景色,但始终拿不到当前行和上一行的单元格文本,导致判断逻辑失效,对吧?
先拆解下核心问题:你用的是TemplateField,每个单元格里嵌套了Label控件,这时候直接访问Cells[1].Text是拿不到实际值的。因为Cells.Text对应的是单元格的原始HTML内容,而不是Label控件里渲染的文本,所以你之前的Debug输出应该都是空字符串,自然判断条件永远不对。
修正后的代码方案
你需要通过FindControl方法找到单元格里的Label控件,再获取它的Text值,上一行的处理也是一样的。修改后的后台代码如下:
protected void gvEscalationLinks_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Debug.WriteLine("e.Row.DataItemIndex: " + e.Row.DataItemIndex); // 获取当前行的SubCategory Label控件及文本 Label currentSubCatLabel = e.Row.FindControl("lblSubCategory") as Label; string currentSubCat = currentSubCatLabel?.Text ?? string.Empty; if (e.Row.DataItemIndex == 0) { e.Row.Cells[1].BackColor = Color.AliceBlue; return; } // 获取上一行的SubCategory Label控件及文本 GridViewRow prevRow = gvEscalationLinks.Rows[e.Row.RowIndex - 1]; Label prevSubCatLabel = prevRow.FindControl("lblSubCategory") as Label; string prevSubCat = prevSubCatLabel?.Text ?? string.Empty; // 对比值并设置背景色 e.Row.Cells[1].BackColor = currentSubCat == prevSubCat ? Color.AliceBlue : Color.White; // 现在Debug可以输出正确的文本值了 Debug.WriteLine("prevSubCat: " + prevSubCat); Debug.WriteLine("currentSubCat: " + currentSubCat); } }
更高效的替代方案
除了找控件,你还可以直接从DataItem里获取绑定的原始值,这种方法不用依赖控件ID,稳定性更高:
protected void gvEscalationLinks_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Debug.WriteLine("e.Row.DataItemIndex: " + e.Row.DataItemIndex); // 把DataItem转换为DataRowView(如果绑定的是DataTable/DataSet) DataRowView rowView = e.Row.DataItem as DataRowView; string currentSubCat = rowView["escSubCategory"].ToString(); if (e.Row.DataItemIndex == 0) { e.Row.Cells[1].BackColor = Color.AliceBlue; return; } // 获取上一行的DataItem值 DataRowView prevRowView = gvEscalationLinks.Rows[e.Row.RowIndex - 1].DataItem as DataRowView; string prevSubCat = prevRowView["escSubCategory"].ToString(); e.Row.Cells[1].BackColor = currentSubCat == prevSubCat ? Color.AliceBlue : Color.White; } }
注:如果你的GridView绑定的是自定义实体类,把
DataRowView换成对应的实体类型即可,比如YourEntityClass row = e.Row.DataItem as YourEntityClass;
为什么之前的代码不行?
简单来说:
- 如果用的是
BoundField,Cells[X].Text可以直接拿到值,因为BoundField会直接把值渲染到单元格的Text属性里。 - 但
TemplateField是自定义模板,单元格里的内容是你放的子控件(比如Label),这时候Cell的Text属性是空的,必须通过子控件才能拿到实际值。
这样修改之后,你的行颜色判断逻辑就能正常工作了。
内容的提问来源于stack exchange,提问作者mpaul
相关产品推荐
相关产品推荐

