2011-01-07 17 views
0

我可以在設計時使用以下設置在ASP.NET網格視圖中將內部對象屬性綁定到gridview我如何在VB.NET中編程綁定<%#Eval(「Object.Property」)%>

<asp:TemplateField HeaderText="ObjectName" > 
          <ItemTemplate>           
              <%# Eval("Object.property")%>          
            </ItemTemplate> 
         </asp:TemplateField> 

,但我希望做知道什麼是在運行時

即編程方式創建這個定義我的專欄,將它們添加到GridView,然後數據綁定

已經沒有人這樣做或有任何指針?

乾杯

回答

1

一個方法是創建一個實現ITemplate接口的類:

public class PropertyTemplate : ITemplate 
{ 
    private string _value = string.Empty; 

    public PropertyTemplate(string propValue) 
    { 
     this._value = propValue; 
    } 

    public void InstantiateIn(Control container) 
    { 
     container.Controls.Add(new LiteralControl(this._value)); 
    } 
} 

然後在你的代碼隱藏assing的ItemTemplate如下:

myTemplateField.ItemTemplate = new PropertyTemplate(myBusinessObject.MyProperty); 

另一種方式將使用Page.LoadTemplate如果您的自定義模板位於單獨的.ascx文件中:

myTemplateField.ItemTemplate = Page.LoadTemplate("~/MyTemplate.ascx"); 

而且.ascx文件看起來像:

<%# Eval("MyProperty") %> 
2

我不知道這是否是你想要達到的目標。但是,如果你想根據自己的對象的對運行屬性的動態創建列,看看下面的代碼(例如是BoundColumns,看看Volpa的答案時,你需要TemplateColumns):

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"></asp:GridView> 

Codebehind:

Public Partial Class GridViewTest 
    Inherits System.Web.UI.Page 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     If Not IsPostBack Then 
      BindData() 
     End If 
    End Sub 

    Private Sub BindData() 
     Dim cList As New List(Of CustomClass) 
     For i As Int32 = 1 To 10 
      Dim c As New CustomClass 
      c.ID = i 
      c.Name = "Object " & i 
      cList.Add(c) 
     Next 
     Dim model As New CustomClass 
     For Each prop As Reflection.PropertyInfo In model.GetType.GetProperties 
      If prop.CanRead Then 
       Dim field As New BoundField() 
       field.HeaderText = prop.Name 
       field.DataField = prop.Name 
       Me.GridView1.Columns.Add(field) 
      End If 
     Next 
     Me.GridView1.DataSource = cList 
     Me.GridView1.DataBind() 
    End Sub 

End Class 

Public Class CustomClass 
    Private _id As Int32 
    Private _name As String 

    Public Property ID() As Int32 
     Get 
      Return _id 
     End Get 
     Set(ByVal value As Int32) 
      _id = value 
     End Set 
    End Property 

    Public Property Name() As String 
     Get 
      Return _name 
     End Get 
     Set(ByVal value As String) 
      _name = value 
     End Set 
    End Property 
End Class 
相關問題