2011-11-25 237 views
3

我在VS2005上使用ASP.NET C#。ASP.NET設置GridView列最大寬度大小

我有一個名爲Description的列的GridView表,並且由於輸入總是非常長,所以描述在水平方向上很長。

我希望GridView的所有列都有最大寬度大小。

我嘗試了很多方法,但都沒有工作。

ItemStyle-Width="50px"

HeaderStyle-BorderWidth="50px"

HeaderStyle-Width="50px"

RowStyle-Width="50px"

Width="50px"

下面是我的GridView的代碼片段:

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"> 
    <Columns> 
     <asp:TemplateField> 
      <ItemTemplate> 
       <asp:CheckBox ID="UserSelector" OnCheckedChanged="UserSelector_CheckedChanged" ondatabound="gv_DataBound" runat="server" /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

任何人都知道如何根據我的情況調整GridView列的大小?

+0

這爲我工作:http://stackoverflow.com/a/17457296/2415524 – mbomb007

回答

3

我改變了我的代碼是你在哪裏思考回合?

 <RowStyle Width="150px"/> 

刪除所有藏匿

<asp:TemplateField><ItemTemplate> </ItemTemplate></asp:TemplateField> 

,只需使用簡單的

<columns> </columns> 

在這裏,我如何,我認爲你的代碼看起來像的AutoGenerateColumns = 「true」 或虛假不要SeeME所要重要

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" DataSourceID="SqlDataSource1"> 
     <Columns> 
      <asp:CheckBox ID="UserSelector" OnCheckedChanged="UserSelector_CheckedChanged" ondatabound="gv_DataBound" runat="server" /> 
     </Columns> 
     <RowStyle Width="150px"/> 
    </asp:GridView> 
+0

@Thomos嗨,你的方法可以應用於在asp選項卡右側調出的列?如何將div實現爲不在asp選項卡中的列,但會在網頁加載時自動顯示,因爲我已將AutoGenerateColumns設置爲true。如果我將它設置爲false,如何在asp選項卡中創建這些列? – gymcode

+0

更改了示例 –

1

y您可以處理RowDataBound事件。

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

檢查此How to: Set GridView Web Server Control Column Width Dynamically瞭解更多詳細信息。

如果你的GridView autogeneratecolumns屬性設置爲false,並且要創建custom columns那麼你可以使用templatefileds在那裏你可以實現TableDiv控制列的寬度。

4

這是我如何控制列寬。

1.在標題中添加CSS。

<style type="text/css"> 
    .maxWidthGrid 
    { 
     max-width: 300px; 
     overflow: hidden; 
    } 
</style> 

2.然後使用CSS在必要的列這樣ItemStyle-CssClass="maxWidthGrid"

<asp:BoundField ItemStyle-CssClass="maxWidthGrid" DataField="ClientName" HeaderText="Client Name" 
        ReadOnly="True" SortExpression="ClientName" /> 
+0

無論出於何種原因,我不得不使用'.maxWidthGrid td'來讓它堅持下去,但這對我有效。 – gaijintendo