撰寫自訂的GridView TemplateField-Part II

撰寫自訂的GridView TemplateField-Part II

接下來我們來實作如何產生我們自訂的TemplateField,

我們先建一個Class名稱為gvTemplate

接著我們Implement Itemplate,

在你程式Implement Itemplate後,會自己帶出的InstantiateIn的副程式

我們在裡面撰寫如下的程式碼


Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
        Select Case templateType
            Case DataControlRowType.Header

                Dim HeaderLesson As New LinkButton

                AddHandler HeaderLesson.Click, AddressOf HeaderLesson_Click
                AddHandler HeaderLesson.DataBinding, AddressOf HeaderLesson_DataBinding
                container.Controls.Add(HeaderLesson)

            Case DataControlRowType.DataRow

                Dim MemberName As New LinkButton()

                AddHandler MemberName.Click, AddressOf MemberName_Click
                AddHandler MemberName.DataBinding, AddressOf MemberName_DataBinding

                container.Controls.Add(MemberName)

            Case Else

        End Select
    End Sub

這邊我區分Header跟跟DataRow出來

那因為我Header跟Row都要給他Linkbutton的事件,所以這邊我2邊都各自New一個LinkButton出來

並且指定他們的DataBind事件、Click事件

而他們的DataBinding事件如下


   Private Sub HeaderLesson_DataBinding(ByVal sender As Object, ByVal e As EventArgs)

        Dim l As LinkButton = CType(sender, LinkButton)

        l.CommandArgument = columnName
        l.Text = columnName

    End Sub

    Private Sub MemberName_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        Dim l As LinkButton = CType(sender, LinkButton)
       
        Dim row As GridViewRow = CType(l.NamingContainer, GridViewRow)

        l.CommandArgument = DataBinder.Eval(row.DataItem, columnName).ToString()
        l.Text = DataBinder.Eval(row.DataItem, columnName).ToString()


    End Sub

 

Click事件如下

 


 Private Sub MemberName_Click(ByVal sender As Object, ByVal e As EventArgs)

        Dim lb As LinkButton = CType(sender, LinkButton)

        ScriptManager.RegisterClientScriptBlock(lb, GetType(LinkButton), "test", "alert('" + lb.CommandArgument + "')", True)

    End Sub

    Private Sub HeaderLesson_Click(ByVal sender As Object, ByVal e As EventArgs)


        Dim lb As LinkButton = CType(sender, LinkButton)

        ScriptManager.RegisterClientScriptBlock(lb, GetType(LinkButton), "test", "alert('" + lb.CommandArgument + "')", True)

    End Sub

 

 

最後別忘了我們的建構子


 Private templateType As DataControlRowType
    Private columnName As String

    Public Sub New(ByVal type As DataControlRowType, ByVal colname As String)
        templateType = type
        columnName = colname

    End Sub