如何以编程方式设置数据绑定GridView的对齐方式?

时间:2011-03-23 11:55:07

标签: asp.net data-binding gridview

这是我的代码:

GridView gv = new GridView();
gv.AutoGenerateColumns = true;
gv.DataSource = listOfEntities;
gv.DataBind();

// set alignment for description column
gv.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Left;

在最后一行,我得到索引超出范围错误,事实上,如果我检查GridView,那么还没有列。我绑定的实体有2个属性,如果我不尝试对齐它们,它们会被渲染出来。

有没有办法在不必动态地将委托分配给gridview的DataBoundEvent的情况下执行此操作?

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

OR

Protected Sub mygridview_Databound(ByVal sender As Object, ByVal e As System.EventArgs) Handles mygridview.DataBound

    Dim gv As GridView = CType(sender, GridView)
    gv.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
    gv.ItemStyle.HorizontalAlign = HorizontalAlign.Left
    gv.FooterStyle.HorizontalAlign = HorizontalAlign.Left

End Sub

答案 1 :(得分:0)

以下是我现在的解决方法:

gv.CssClass = "left-aligned-text";

table.left-aligned-text td
{
   text-align: left;  
}