ASP.NET中如何判断GridView行是否为空及隐藏空行DropDownList
解决GridView空行时DropDownList莫名显示的问题
我明白你的困扰——页面加载时GridView是空的,但RowDataBound里加的DropDownList还是冒出来了,想要让它只在行内有实际内容时才显示对吧?咱们分两种场景来处理:
直接修改现有代码的方案
如果你的DropDownList是在ASPX页面里声明好的,那只要在RowDataBound里加个判断,检查对应单元格是否为空,再控制DropDownList的可见性就行:
protected void grw_RowDataBound(object sender, GridViewRowEventArgs e) { // 先处理正常的数据行 if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddl = e.Row.FindControl("ddlAccepted") as DropDownList; Label lblAccepted = e.Row.FindControl("lblAccepted") as Label; // 先确保控件都找到,避免空引用报错 if (ddl != null && lblAccepted != null) { // 这里用IsNullOrWhiteSpace,连空格、换行这种空白字符也能判断 if (string.IsNullOrWhiteSpace(lblAccepted.Text)) { ddl.Visible = false; } else { // 这里放你原本设置DropDownList的逻辑,比如绑定选中项 string acceptedKey = lblAccepted.Text; // ... 你的其他代码 } } } // 别忘了处理GridView无数据时的空行! else if (e.Row.RowType == DataControlRowType.EmptyDataRow) { DropDownList ddl = e.Row.FindControl("ddlAccepted") as DropDownList; if (ddl != null) { ddl.Visible = false; } } }
要是你是动态添加DropDownList的情况
如果DropDownList是你在代码里动态加到最后一个单元格的,那更简单——只有当行内有实际数据的时候再添加它:
protected void grw_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // 先检查当前行有没有有效数据 bool rowHasData = false; foreach (TableCell cell in e.Row.Cells) { if (!string.IsNullOrWhiteSpace(cell.Text)) { rowHasData = true; break; } } if (rowHasData) { // 动态创建DropDownList DropDownList ddl = new DropDownList(); ddl.ID = "ddlAccepted"; // 添加选项、设置属性等逻辑... // 加到最后一个单元格里 TableCell lastCell = e.Row.Cells[e.Row.Cells.Count - 1]; lastCell.Controls.Add(ddl); // 继续你的其他逻辑,比如设置选中项 string acceptedKey = (e.Row.FindControl("lblAccepted") as Label)?.Text; // ... } // 要是行里没数据,直接跳过添加控件,自然就看不到了 } }
关键要点提醒
- 别漏了
EmptyDataRow:GridView没数据时显示的空行,它的RowType不是DataRow,所以单独判断才能隐藏这里的DropDownList。 - 用
string.IsNullOrWhiteSpace():比单纯判断Text == ""靠谱,能覆盖用户输入空格这种情况。 - 空值检查:每次FindControl后都判断是否为null,避免运行时报空引用异常。
内容的提问来源于stack exchange,提问作者DM Ibtissam
相关产品推荐
相关产品推荐

