在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; } } }