Asp.net 设置GridView自适应列宽不变形

动态绑定的GridView由于列数不固定,而列又太多,这样设置GridView固定宽度就不能满足需求了。为此整理了两种方法来达到GridView自适应列宽不变形的效果。

    //在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标记的方式实现不换行; 就是一个空格,可以让网格线和里面的内容留有一定的距离保持美观。

有兴趣的朋友,动手下吧,看看效果如何哦。

posted @ 2014-11-21 10:03  灵雨飘零  阅读(7460)  评论(0编辑  收藏  举报