ASP.NET GridView字段截断显示省略号及Tooltip功能失效求助
解决方案
问题出在使用TemplateField时,单元格的Text属性不再直接存储字段内容——因为单元格内部包含的是LinkButton或Label控件,而非纯文本。你需要直接定位到这些控件,修改它们的Text和ToolTip属性。
替换原有的ItemView_RowDataBound方法为以下代码:
protected void ItemView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // 处理Item字段(btn_Select控件) LinkButton btnSelect = e.Row.FindControl("btn_Select") as LinkButton; if (btnSelect != null) { string fullText = btnSelect.Text; int maxLength = 50; if (!string.IsNullOrEmpty(fullText) && fullText.Length > maxLength) { btnSelect.Text = fullText.Substring(0, maxLength) + "..."; } btnSelect.ToolTip = fullText; } // 处理Tech Notes字段(lbl_techNotes控件) Label lblTechNotes = e.Row.FindControl("lbl_techNotes") as Label; if (lblTechNotes != null) { string fullText = lblTechNotes.Text; int maxLength = 50; // 跳过NullDisplayText的"--",无需截断 if (!string.IsNullOrEmpty(fullText) && fullText != "--" && fullText.Length > maxLength) { lblTechNotes.Text = fullText.Substring(0, maxLength) + "..."; } lblTechNotes.ToolTip = fullText; } } }
关键说明
- 直接定位控件:使用
FindControl通过控件ID获取目标元素,比依赖列索引更可靠(避免列顺序调整后失效)。 - 处理空值与默认文本:针对
lbl_techNotes的NullDisplayText(即"--")做了判断,避免对默认文本进行不必要的截断。 - 保留完整Tooltip:无论文本是否截断,都将原始完整文本设置为控件的
ToolTip,确保鼠标悬停时显示全部内容。
内容的提问来源于stack exchange,提问作者Amy
相关产品推荐
相关产品推荐

