在gridview和datagrid里设置列宽

无论是gridview还是datagrid,在绑定数据后,列宽都不是固定的,在设计时是没法设定的,只能通过绑定是触发的事件来重新设定。参考http://msdn2.microsoft.com/zh-cn/library/ms178296(VS.80).aspx 的解释。

gridview的代码:

protected int widestData;
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
System.Data.DataRowView drv;
drv = (System.Data.DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv != null)
{
String catName = drv[1].ToString();
Response.Write(catName + ?¡ã/?¡À);
int catNameLen = catName.Length;
if (catNameLen > widestData)
{
widestData = catNameLen;
GridView1.Columns[2].ItemStyle.Width =
widestData * 30;
GridView1.Columns[2].ItemStyle.Wrap = false;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
widestData = 0;
}

datagrid 的代码:

protected void datagrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Header)
{
for (int i = 0; i < e.Item.Cells.Count; i++)
{
e.Item.Cells[i].Width = Unit.Pixel(80);
e.Item.Cells[i].Wrap = false;
}
}
}
本文首发地址:http://www.watch-life.net/aspnet/gridview-datagrid-column-width.html
---------------------------------------------------------------------
更多文章见:守望轩[http://www.watch-life.net]
 

posted on 2008-01-17 12:27  xjb  阅读(1436)  评论(0编辑  收藏  举报

导航