c#中,如何设置,datagrid工作区中网格的大小宽高度,我找到一个datagrid.preferredColumnWidth属性,不知道怎么用,以为显示出来的数据,有的数据不会显示很多,而又的数据会显示很多(比如地址),我现在想根据数据的多少,让网格自动调整每一列的宽度,好显示内容,我现在默认的是,数据区中每个显示出来的数据列,都是相同的!请问该怎么解决!请给出相应代码!,一旦解决,马上接贴

解决方案 »

  1.   

    每个datagrid的列都有一个ItemStyle-Width属性的,这个可以控制宽度
    比如
    <asp:datagrid id="dgEducations" runat="server" BorderWidth="0px" Width="100%" ShowHeader="False"
    CssClass="table" CellPadding="5" AutoGenerateColumns="False">
    <SelectedItemStyle BackColor="#CCCCFF"></SelectedItemStyle>
    <AlternatingItemStyle BackColor="#E0E0E0"></AlternatingItemStyle>
    <Columns>
    <asp:BoundColumn Visible="False" DataField="ID"></asp:BoundColumn>
    <asp:TemplateColumn ItemStyle-Width="30px">
    <HeaderStyle Width="30px"></HeaderStyle>
    <ItemTemplate>
    <IMG alt="" src="../image/ico3.gif">&nbsp;
    </ItemTemplate>
    </asp:TemplateColumn>
    <asp:BoundColumn DataField="Date" ItemStyle-Width="100px"></asp:BoundColumn>
    <asp:BoundColumn DataField="SchoolName"></asp:BoundColumn>
    <asp:BoundColumn DataField="Zhuanye"></asp:BoundColumn>
    <asp:BoundColumn DataField="XueLi_Type"></asp:BoundColumn>
    <asp:TemplateColumn ItemStyle-Width="100px">
    <HeaderTemplate>
    <FONT face="宋体"></FONT>
    </HeaderTemplate>
    <ItemTemplate>
    <FONT face="宋体">
    <asp:LinkButton id="btnMod" runat="server" CommandName="MODIFY" CausesValidation="False">修改</asp:LinkButton>&nbsp;|
    <asp:LinkButton id="btnDel" runat="server" CommandName="DELETE" CausesValidation="False">删除</asp:LinkButton></FONT>
    </ItemTemplate>
    <FooterTemplate>
    <FONT face="宋体"></FONT>
    </FooterTemplate>
    <EditItemTemplate>
    <FONT face="宋体"></FONT>
    </EditItemTemplate>
    </asp:TemplateColumn>
    </Columns>
    </asp:datagrid>
      

  2.   

    不好意思,我写的是windows应用程序阿,不过还是谢谢你!
      

  3.   

    One way to do this is to use MeasureString to compute the size of the text in each cell, and then take the maximum value. Below is a code snippet that does this. It assumes your datagrid is bound to a datatable. You can download a full working sample. (C#,VB). 
     
    public void AutoSizeCol(int col) 
     

     
         float width = 0; 
     
         int numRows = ((DataTable) dataGrid1.DataSource).Rows.Count; 
     
               
     
         Graphics g = Graphics.FromHwnd(dataGrid1.Handle); 
     
         StringFormat sf = new StringFormat(StringFormat.GenericTypographic); 
     
         SizeF size; 
      
         for(int i = 0; i < numRows; ++ i) 
     
         { 
     
              size = g.MeasureString(dataGrid1[i, col].ToString(), dataGrid1.Font, 500, sf); 
     
              if(size.Width > width) 
     
                   width = size.Width; 
     
         } 
      
         g.Dispose(); 
      
         dataGrid1.TableStyles["customers"].GridColumnStyles[col].Width = (int) width + 8; // 8 is for leading and trailing padding 
     
    }