Search code examples
asp.netvb.netvisual-studio-2008datagridalignment

How to apply column alignment to datagrid


I have an VB.Net ASP page that I have a datagrid on it with 5 columns and a few rows of data. The page will show the data and grid just fine. I need to now apply alignment to the datagrid columns.

dgLast5Bills.DataSource = dtBill
dgLast5Bills.DataBind()
dgLast5Bills.Columns(0).ItemStyle.HorizontalAlign = HorizontalAlign.Center

The code above will error out when it hits the line for the alignment. What am I doing wrong?

Thanks


Solution

  • Your dgLast5Bills.Columns(0).ItemStyle.HorizontalAlign = HorizontalAlign.Center code give you Index was out of range error because in your aspx page you have not define any column, so at compile time there is no 0 index.

    You should try this.

      Sub Item_Bound(sender As Object, e As DataGridItemEventArgs) 
         If e.Item.ItemType = ListItemType.Item Then
             e.Item.Cells(0).HorizontalAlign = HorizontalAlign.Center
         End If         
      End Sub
    

    For more reading look at it. DataGrid.ItemDataBound Event