在gridview和datagrid里设置列宽

时间:2022-04-21
本文章向大家介绍在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;
                }
            }
        }

本文地址://www.watch-life.net/aspnet/gridview-datagrid-column-width.html