2012-05-30 24 views
0

我有一個gridview自動生成的列,我以編程方式設置我想格式化列寬。這是我對我的背後代碼GridView的代碼...格式GridView

If Not Page.IsPostBack Then 
    Dim budgetTable As New DataTable("Budgets") 

    budgetTable.Columns.Add("Approval Date", GetType(Date)) 
    budgetTable.Columns.Add("Total Amount", GetType(String)) 
    budgetTable.Columns.Add("Comments", GetType(String)) 
    budgetTable.Columns.Add("Initials", GetType(String)) 

    Try 
     For i As Integer = 0 To 0 
      Dim tableRow As DataRow = budgetTable.NewRow() 
      tableRow("Approval Date") = Date.Today 
      tableRow("Total Amount") = "" 
      tableRow("Comments") = "" 
      tableRow("Initials") = "" 
      budgetTable.Rows.Add (tableRow) 
     Next 
     Session("BudgetsTable") = budgetTable 
     BindData() 
    Catch ex As Exception 

    End Try 
End If 

而且這是在HTML側GridView控件:

<asp:GridView ID="gvOLIAdj" runat="server" CssClass="td8" CellPadding="4" ForeColor="#333333" PageSize="2" ViewStateMode="Enabled"> 
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 

    <Columns> 
     <asp:CommandField EditText="Add" ShowEditButton="True" /> 
    </Columns> 

    <EditRowStyle BackColor="#999999" /> 
    <FooterStyle BackColor="#003399" Font-Bold="True" ForeColor="White" /> 
    <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" /> 
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
    <SortedAscendingCellStyle BackColor="#E9E7E2" /> 
    <SortedAscendingHeaderStyle BackColor="#506C8C" /> 
    <SortedDescendingCellStyle BackColor="#FFFDF8" /> 
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
</asp:GridView> 
+0

這與VBA有什麼關係? –

+0

我需要它在vb格式 – developthestars

+0

重複? - > http://stackoverflow.com/questions/546299/gridview-column-width-altering – rt2800

回答

1

- 編輯 -

(去除舊的內容,因爲這將不會幫助)

嘗試使用RowDataBound事件來設置寬度(或任何其他屬性)。

未經測試的代碼:

Protected Sub gvOLIAdj_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvOLIAdj.RowDataBound 
    If (e.Row.RowType = DataControlRowType.Header) Then 
     e.Row.Cells(0).Width = 100 '100 pixels 
     e.Row.Cells(1).Width = 50 
     e.Row.Cells(2).Width = 200 
     e.Row.Cells(3).Width = 150 
    End If 
End Sub 

如果上述方法無效,請嘗試將它e.Row.RowType = DataControlRowType.DataRow

+0

@ rt2800和Predeep Kumar ...我嘗試了這兩個選項,我首先看到帖子...我不斷收到一條錯誤消息「索引超出範圍,必須是非負數,小於集合的大小。名稱:索引「只要我打我的第一個動態創建列? – developthestars

+0

好的..我的壞。我只是忘記了你正在使用動態生成的列。列集合未針對動態生成的列進行更新(出於某種原因或其他原因,只有控制創建者才知道)。所以上界仍然爲0.因此,你不能通過列號來解決它們。 –

+0

更新了上面的代碼。試試看看它是否有任何幫助:) –

0

我會用樣式表來完成它:

.td8 td:nth-child(3) { 
    width: 100px; 
} 

假設你想要的第三列是100像素。這是一個CSS3選項,所以它只能用於較新的瀏覽器。

編輯: 閱讀您對@Pradeep Kumar所做的評論,您可能會過早地將寬度應用於列。在綁定並創建GridView後,嘗試在Page_PreRender事件中進行這些更改。請記住,GridView中的列在之後才存在, RowItemCreated事件已完全完成。

+0

感謝大家的幫助,但沒有任何工作......我即將放棄。大聲笑 – developthestars

+0

@developthestars:你的樣本中沒有包含的一段代碼就是你實際試圖設置寬度的地方。也許如果你分享了你甚至試圖這樣做,我們可能會更有幫助。 –