Asp.net简单代码设置GridView自适应列宽不变形实现思路与代码

 更新时间:2021年9月22日 10:17  点击:2278
动态绑定的GridView由于列数不固定,而列又太多(博主做的这个项目有150个左右的字段),这样设置GridView固定宽度就不能满足需求了。为此整理了两种方法来达到GridView自适应列宽不变形的效果。
.aspx.cs
复制代码 代码如下:

//在GridView的行数据绑定完的事件中设置
protected void gvObjectList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
{
//保持列不变形
for (int i = 0; i < e.Row.Cells.Count; i++)
{
//方法一:
e.Row.Cells[i].Text = "&nbsp;" + e.Row.Cells[i].Text + "&nbsp;";
e.Row.Cells[i].Wrap = false;
//方法二:
//e.Row.Cells[i].Text = "<nobr>&nbsp;" + e.Row.Cells[i].Text + "&nbsp;</nobr>";
}
}
}

方法一是设置cell的自动换行属性为false,方法二是用html标记的方式实现不换行;&nbsp;就是一个空格,可以让网格线和里面的内容留有一定的距离保持美观。
[!--infotagslink--]

相关文章