Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Jun 2006
    Posts
    72

    Unanswered: Gridview header template

    Hello, I am using VS 2008 ASP.net and I'm programming with VB, not C. Also I'm connecting to an SQL server database.

    This is a link to a picture of a gridveiw that I have programmed.

    You will notice that two of the columns have controls in them for setting all the values going down. Both work as intended.

    The arrow in the picture points to where I wish to add an "add all" and an "rem all" button. I wish to add these buttons to all the columns going across from that point onward.

    The column that is pointed to and all those after it are created in runtime based on the query generated by the selections made by the user.

    I cannot work out how to add a control to the header template of a dynamically generated column.

    The code that I use to add the columns works and can be found below...

    Code:
                i = 0
                While r.Read()
                    Dim MPTVID As Integer = CInt(r("MPTVID"))
                    Dim ShortMeth As String = r("ShortName")
                    Dim ShortProd As String = r("ProdShort")
                    Dim ShortTech As String = r("TechShort")
                    Dim ShortVer As String = r("Version")
                    Dim AddColumn As New ButtonField()
                    AddColumn.HeaderText = ShortMeth + vbNewLine + ShortProd + vbNewLine + ShortTech + vbNewLine + "Ver " + ShortVer
                    AddColumn.ItemStyle.Width = 4
                    AddColumn.CommandName = MPTVID
                    AddColumn.ButtonType = ButtonType.Link
                    AddColumn.DataTextField = MPTVID
                    AddColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center
                    gvTestGrid.Columns.Add(AddColumn)
                    i += 1
                End While
    After searching online my best attempt at achieving this can be found below.

    Code:
                    Dim cmdTest As WebControls.Button
                    cmdTest = New WebControls.Button()
                    cmdTest.Text = "hello"
                    cmdTest.Visible = True
                    cmdTest.ID = "testID"
                    cmdTest.BorderWidth = "0"
                    cmdTest.CssClass = "testbutton"
                    gvTestGrid.HeaderRow.Cells(i).Controls.Add(cmdTest)
    The above code is placed within the while loop.

    The error that I get is "Object reference not set to an instance of an object.".

    **I should have mentioned that the error is on the last line. "gvTestGrid.HeaderRow.Cells(i).Controls.Add(cmdTes t)"


    I may be way off with this code all together and I will continue to try to find a solution online but any suggestions will be appreciated.
    Last edited by Access Junkie; 11-03-09 at 05:30.

  2. #2
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    In what event are you attempting to manipulate the HeaderRow?

    Also, have you set a breakpoint and checked gvTestGrid.HeaderRow.Cells(i) and cmdTest separately to figure out which object doesn't appear to be present?
    Last edited by Teddy; 11-03-09 at 20:48.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  3. #3
    Join Date
    Jun 2006
    Posts
    72
    Teddy, thank you for your response .

    There is a set of drop down lists at the top of the page. Below them is a button which when pressed generates the gridview based on the selections in the drop downs made by the user.

    It is in the onclick event for that button.

    It was actually gvTestGrid.HeaderRow.Cells(i) which was not present. I'm glad you asked the question also because if I have now found that if I put the code that was not working after the databind for the gridview it works.

    I suppose I should have included a more complete chunk of my code in the first place.

    My newest problem is that while the button will now add to the heading, it will not remain after a postback.

    My newest version of code is below.

    Code:
        Private Sub cmdPlanning_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdPlanning.Click
            Dim i As Integer
            Dim SQL As String, SQLSelect As String, SQLIn As String
            Dim sqlconn As New SqlConnection
    
            sqlconn.ConnectionString = SQLConnString
            sqlconn.Open()
    
            Dim sqlCommSP As New SqlCommand("CreateTemporaryPlanningTable2", sqlconn)
    
            sqlCommSP.CommandType = CommandType.StoredProcedure
            sqlCommSP.Parameters.AddWithValue("Trial", ddlistTrial.SelectedValue.ToString)
            sqlCommSP.Parameters.AddWithValue("ReportGroup", ddlistReportGroup.SelectedValue.ToString)
            RepID = CLng(sqlCommSP.ExecuteScalar())
    
            SQL = "SELECT DISTINCT MethProdTechVerLists.MPTVID, Methods.ShortName, ProductsTested.ShortDesc AS ProdShort,  " _
                    + "Techniques.ShortDesc AS TechShort, ResultDetails.Version, MethProdTechVerLists.[Order] " _
                + "FROM MethProdTechVerLists INNER JOIN " _
                      + "ResultDetails ON MethProdTechVerLists.MPTVID = ResultDetails.MPTVID INNER JOIN " _
                      + "Methods ON ResultDetails.MethodID = Methods.MethodID INNER JOIN " _
                      + "ProductsTested ON ResultDetails.ProductTested = ProductsTested.ProductTested INNER JOIN " _
                      + "Techniques ON ResultDetails.Technique = Techniques.Technique " _
                + "WHERE MethProdTechVerLists.ReportGroupID='" + ddlistReportGroup.SelectedValue.ToString + "' " _
                + "ORDER BY MethProdTechVerLists.[Order]"
            Dim sqlComm As New SqlCommand(SQL, sqlconn)
            Dim r As SqlDataReader = sqlComm.ExecuteReader()
    
            If r.HasRows() Then
                For i = 14 To gvTestGrid.Columns.Count - 1
                    gvTestGrid.Columns.Remove(gvTestGrid.Columns(14))
                Next
                SQLIn = ""
                SQLSelect = ""
                i = 0
                While r.Read()
                    Dim MPTVID As Integer = CInt(r("MPTVID"))
                    Dim ShortMeth As String = r("ShortName")
                    Dim ShortProd As String = r("ProdShort")
                    Dim ShortTech As String = r("TechShort")
                    Dim ShortVer As String = r("Version")
                    Dim AddColumn As New ButtonField()
    
                    SQLIn = SQLIn + "[" + MPTVID.ToString + "], "
                    SQLSelect = SQLSelect + "CASE WHEN [" + MPTVID.ToString + "]=-1 THEN 'N' ELSE CASE WHEN [" + MPTVID.ToString + "]=0 THEN 'P' ELSE CAST([" + MPTVID.ToString + "] AS VARCHAR(50)) END END AS [" + MPTVID.ToString + "], "
                    AddColumn.HeaderText = ShortMeth + vbNewLine + ShortProd + vbNewLine + ShortTech + vbNewLine + "Ver " + ShortVer
                    AddColumn.ItemStyle.Width = 4
                    AddColumn.CommandName = MPTVID
                    AddColumn.ButtonType = ButtonType.Link
                    AddColumn.DataTextField = MPTVID
                    AddColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center
                    gvTestGrid.Columns.Add(AddColumn)
    
                    i += 1
                End While
                r.Close()
                SQLIn = Left(SQLIn, Len(SQLIn) - 2)
                SQLSelect = Left(SQLSelect, Len(SQLSelect) - 2)
    
                SQL = "SELECT RepID, SeriesShort, TrialRego, [Level], TreatmentID, SampleBarcode, VarietyTestName, SampleLabNumber, SampleExists, " + SQLSelect + " " _
                    + "FROM TempPlanningTables " _
                    + "PIVOT " _
                    + "(" _
                    + "SUM(Planned) FOR MPTVID IN (" + SQLIn + ")" _
                    + ") AS pvt " _
                    + "WHERE RepID=" + RepID.ToString + " " _
                    + "ORDER BY SampleExists DESC, SampleLabNumber"
    
                sdsPlanningTable.ConnectionString = SQLConnString
                sdsPlanningTable.SelectCommand = SQL
                gvTestGrid.DataSource = sdsPlanningTable
                gvTestGrid.DataBind()
    
                Dim cmdTest As WebControls.Button
                cmdTest = New WebControls.Button()
                cmdTest.Text = "hello"
                cmdTest.Visible = True
                cmdTest.ID = "testID"
                cmdTest.BorderWidth = "0"
                cmdTest.CssClass = "testbutton"
                gvTestGrid.HeaderRow.Cells(10).Controls.Add(cmdTest)
    
                cmdPlanAll.Visible = True
                cmdPlanNone.Visible = True
            Else
                Dim lblFail = New System.Web.UI.WebControls.Label
                lblFail.Text = "The selected trial/report group combination did not yeild any results. Please try selecting a different trial or report group."
                PlaceHolder.Controls.Add(lblFail)
                cmdPlanAll.Visible = False
                cmdPlanNone.Visible = False
            End If
        End Sub
    As you can probably already tell this will only add a button to one column. Eventually I will have to rewrite to code so that it adds what I actually want to all the columns. First I want to make it so that the button will not disappear on postback.

    One obvious option that would probably work is to add the buttons to the grid again after every postback event. I am hoping that there is a better solution.
    Last edited by Access Junkie; 11-03-09 at 21:41.

  4. #4
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    Unfortunately there isn't. Dynamically created controls simply don't exist on postback due to the stateless nature of http. Since you are creating the controls after viewstate gets wired up (just before page_load), you won't get viewstate or event firing for your dynamically created controls.

    You might want to fake it out with a hidden control that will store relevant information to be handled on postback. You can then populate that control with a bit of javascript. Another option would be to use the "clientside callback" facilities provided with the framework.


    Edit: Read up on SQL injection and using prepared statements. You've got some problems there. Also, you might find the StringBuilder class to be useful.
    Last edited by Teddy; 11-03-09 at 23:57.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  5. #5
    Join Date
    Jun 2006
    Posts
    72
    I'm not ready to give up quite yet. I've found what might be a way to do it.

    I found this site while searching for a way to do this.

    In my original post you will see the columns going across with links as controls. Those columns are generated dynamically and they do not disappear after a postback. Also their events work.

    The difference here is that I added them before the databind using gvTestGrid.Columns.Add(AddColumn).

    I assumed that if I could add a column in the same way where it has a header with controls, those controls will not be lost and their events will work.

    It partly works. Below you will find my code for adding the columns with controls in both the item template and in the header template.

    Code:
        Private Sub cmdPlanning_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdPlanning.Click
            Dim i As Integer
            Dim SQL As String, SQLSelect As String, SQLIn As String
            Dim sqlconn As New SqlConnection
    
            sqlconn.ConnectionString = SQLConnString
            sqlconn.Open()
    
            Dim sqlCommSP As New SqlCommand("CreateTemporaryPlanningTable2", sqlconn)
    
            sqlCommSP.CommandType = CommandType.StoredProcedure
            sqlCommSP.Parameters.AddWithValue("Trial", ddlistTrial.SelectedValue.ToString)
            sqlCommSP.Parameters.AddWithValue("ReportGroup", ddlistReportGroup.SelectedValue.ToString)
            RepID = CLng(sqlCommSP.ExecuteScalar())
    
            SQL = "SELECT DISTINCT MethProdTechVerLists.MPTVID, Methods.ShortName, ProductsTested.ShortDesc AS ProdShort,  " _
                    + "Techniques.ShortDesc AS TechShort, ResultDetails.Version, MethProdTechVerLists.[Order] " _
                + "FROM MethProdTechVerLists INNER JOIN " _
                      + "ResultDetails ON MethProdTechVerLists.MPTVID = ResultDetails.MPTVID INNER JOIN " _
                      + "Methods ON ResultDetails.MethodID = Methods.MethodID INNER JOIN " _
                      + "ProductsTested ON ResultDetails.ProductTested = ProductsTested.ProductTested INNER JOIN " _
                      + "Techniques ON ResultDetails.Technique = Techniques.Technique " _
                + "WHERE MethProdTechVerLists.ReportGroupID='" + ddlistReportGroup.SelectedValue.ToString + "' " _
                + "ORDER BY MethProdTechVerLists.[Order]"
            Dim sqlComm As New SqlCommand(SQL, sqlconn)
            Dim r As SqlDataReader = sqlComm.ExecuteReader()
    
            If r.HasRows() Then
                For i = 14 To gvTestGrid.Columns.Count - 1
                    gvTestGrid.Columns.Remove(gvTestGrid.Columns(14))
                Next
                SQLIn = ""
                SQLSelect = ""
                i = 0
                While r.Read()
                    Dim MPTVID As Integer = CInt(r("MPTVID"))
                    Dim ShortMeth As String = r("ShortName")
                    Dim ShortProd As String = r("ProdShort")
                    Dim ShortTech As String = r("TechShort")
                    Dim ShortVer As String = r("Version")
                    Dim AddColumn As New ButtonField()
    
                    Dim tf As New TemplateField
                    Dim item As New MyTemplate()
    
                    tf.ItemTemplate = item
                    tf.HeaderTemplate = item
    
                    gvTestGrid.Columns.Add(tf)
    
                    SQLIn = SQLIn + "[" + MPTVID.ToString + "], "
                    SQLSelect = SQLSelect + "CASE WHEN [" + MPTVID.ToString + "]=-1 THEN 'N' ELSE CASE WHEN [" + MPTVID.ToString + "]=0 THEN 'P' ELSE CAST([" + MPTVID.ToString + "] AS VARCHAR(50)) END END AS [" + MPTVID.ToString + "], "
                    'AddColumn.HeaderText = ShortMeth + vbNewLine + ShortProd + vbNewLine + ShortTech + vbNewLine + "Ver " + ShortVer
                    'AddColumn.ItemStyle.Width = 4
                    'AddColumn.CommandName = MPTVID
                    'AddColumn.ButtonType = ButtonType.Link
                    'AddColumn.DataTextField = MPTVID
                    'AddColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center
                    'gvTestGrid.Columns.Add(AddColumn)
    
                    i += 1
                End While
                r.Close()
                SQLIn = Left(SQLIn, Len(SQLIn) - 2)
                SQLSelect = Left(SQLSelect, Len(SQLSelect) - 2)
    
                SQL = "SELECT RepID, SeriesShort, TrialRego, [Level], TreatmentID, SampleBarcode, VarietyTestName, SampleLabNumber, SampleExists, " + SQLSelect + " " _
                    + "FROM TempPlanningTables " _
                    + "PIVOT " _
                    + "(" _
                    + "SUM(Planned) FOR MPTVID IN (" + SQLIn + ")" _
                    + ") AS pvt " _
                    + "WHERE RepID=" + RepID.ToString + " " _
                    + "ORDER BY SampleExists DESC, SampleLabNumber"
    
                sdsPlanningTable.ConnectionString = SQLConnString
                sdsPlanningTable.SelectCommand = SQL
    
                gvTestGrid.DataSource = sdsPlanningTable
                gvTestGrid.DataBind()
    
                cmdPlanAll.Visible = True
                cmdPlanNone.Visible = True
            Else
                Dim lblFail = New System.Web.UI.WebControls.Label
                lblFail.Text = "The selected trial/report group combination did not yeild any results. Please try selecting a different trial or report group."
                PlaceHolder.Controls.Add(lblFail)
                cmdPlanAll.Visible = False
                cmdPlanNone.Visible = False
            End If
        End Sub
    Below is the MyTemplate class code.

    Code:
        Private Class MyTemplate
            Implements ITemplate
            'Expose the command event handler - when the command event handler is trapped internally this event is raised to inform the container 
            Public Event LinkButtonCommand As CommandEventHandler
            'Public Event LinkButtonClick As EventHandler 
    
            Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
                Dim text As New Label
                text.Style.Add("display", "block")
                text.Style.Add("width", "80px")
                text.Style.Add("float", "left")
    
                AddHandler text.DataBinding, AddressOf Me.BindText
                container.Controls.Add(text)
    
    
                Dim lnkBtn As New LinkButton
                lnkBtn.Style.Add("float", "left")
                AddHandler lnkBtn.DataBinding, AddressOf Me.BindLinkButtons
                'AddHandler lnkBtn.Click, New EventHandler(AddressOf Click) 
                AddHandler lnkBtn.Command, New CommandEventHandler(AddressOf Command)
                container.Controls.Add(lnkBtn)
            End Sub
    
            Private Sub BindLinkButtons(ByVal sender As Object, ByVal e As EventArgs)
                Dim lnkBtn As LinkButton = CType(sender, LinkButton)
                Dim container As GridViewRow = CType(lnkBtn.NamingContainer, GridViewRow)
                'Dim cellContent As String '= DataBinder.Eval(container.DataItem, "Content").ToString
                lnkBtn.Text = "test"
                lnkBtn.CommandArgument = "Sort"
    
            End Sub
            Private Sub BindText(ByVal sender As Object, ByVal e As EventArgs)
                Dim txt As Label = CType(sender, Label)
                Dim row As GridViewRow = CType(txt.NamingContainer, GridViewRow)
                'Dim cellContent As String = DataBinder.Eval(row.DataItem, "Title").ToString
                txt.Text = "test" + ": "
            End Sub
    
            ''This will crash because the only event that's bubbled up is the Command Event....which takes a parameter of CommandEventArgs 
            'Private Sub Click(ByVal sender As Object, ByVal e As EventArgs) 
            '    RaiseEvent LinkButtonClick(Me, e) 
            'End Sub 
    
            'Handles the Command Event:  
            'When the link button is clicked the Command event is bubbled up to the container, which happens to be this class. 
            'This method bubbles the event up to the next level so that the event can be 
            'handled in the Page. 
            Private Sub Command(ByVal sender As Object, ByVal e As CommandEventArgs)
                RaiseEvent LinkButtonCommand(Me, e)
            End Sub
        End Class
    Unfortunately it still disappears on postback. Maybe this simply is not possible but I'm going to keep trying because I don't see why this shouldn't work.

    In case it is at all helpful, the output from this code is here

  6. #6
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    do you understand that your template is recreating controls on every postback?

    Also, handling a declaratively defined GridView's OnCommand event is very different from handling a dynamically created button's click event when that button wasn't created oninit.


    Look VERY closely at the explanation for how that code you found works...

    Particularly this part:
    The first thing to note is that you Must create your columns in your Page Init Event.
    If you do not do this, the events for the controls created dynamically in your template will be lost. They will post back to the server, but then the event cease to exist.
    When are you creating your button?




    You're comparing apples and apes by expecting adding columns to a gridview's column collection to be the same as manipulating the header. Columns may provide some capabilities for storing header text, but that's where the similarities end.

    You might also see some benefit by reading up on DataControlField's and understanding how what you're doing now actually works.
    Last edited by Teddy; 11-04-09 at 00:26.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  7. #7
    Join Date
    Jun 2006
    Posts
    72
    I realized that after I made my post.

    So basically if I create and add the columns during page init, it will work?

    I think I can live with this solution given the added functionality that I will gain from it.

    This creates a new problem, the ddlistReportGroup.SelectedValue.ToString value does not seem to exist in the page init event.

    If I can get past this last little problem I think I can make this work.

    Thank you for your help Teddy .

  8. #8
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    You're seeing that issue because viewstate (which contains information about how/what the user did) is wired up after init.

    It won't exist until on_load().

    If it were me, I'd ghetto it up and go with the hidden control method that gets populated when the user selects something from the dropdown.
    Last edited by Teddy; 11-04-09 at 00:39.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  9. #9
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    Also, check this out as I think it will answer a lot of your questions. I keep a Cheat Sheet Version printed out wherever I'm working as it's a good quick-reference:

    ASP.NET Page Life Cycle Overview

    There's a section in there for databound controls that should clear up some of the murky business you're running in to. Of particular note is the header row is just another row, it's merely a different kind of row. As such, it is created at the same time as all the other rows...
    Last edited by Teddy; 11-04-09 at 00:52.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  10. #10
    Join Date
    Jun 2006
    Posts
    72
    Ok, for the life of me, I cannot work out how to get a value in the page init event.

    You said "If it were me, I'd ghetto it up and go with the hidden control method that gets populated when the user selects something from the dropdown.", would you mind translating that into code?

  11. #11
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    I can dig something up for you tomorrow if you haven't sorted it by then.

    All you need to do is created a hidden field:

    <input type="hidden" name="MyHiddenField" />

    then add an onChange javascript event to your dropdown list that does nothing other than something like this:

    onChange="GhettoField(this)"

    function GhettoField (sender)
    {
    myField = forms[0].elements("MyHiddenField");

    myField.value = sender.options[sender.selectedindex].value;
    }


    Now on postback if you pull Request.params["MyHiddenField"] you'll have access to the value, since you side-stepped the whole .NET/viewstate wireup thing and opted to manipulate a regular-ol' html control with javascript via the DOM. Remember, ASP.NET is nothing special as far as the browser is concerned. You don't HAVE to rely on the built in markup and eventing model to pass state information around.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  12. #12
    Join Date
    Jun 2006
    Posts
    72
    Any chance that you could translate that into vb script?

    I tried myself by writting,

    Code:
    <script runat="server">
        Public Sub GhettoField(ByVal sender As Object)
            
            Dim myField As Object = Forms(0).elements("MyHiddenField")
    
            myField.value = sender.options(sender.selectedindex).value
        
        End Sub
    </script>
    It does not recognise forms. It says "Name Forms is not declared."

  13. #13
    Join Date
    Jun 2006
    Posts
    72
    Nevermind my last post.

    It is passing the parameter that I need into the page_init event now .

    I tried to apply the solution but for some reason it only added 4 columns when it should have added a lot more.

    I had suspicions about why but in my attempt to fix this, I've managed to break the whole thing.

    I'll come back and update when I've got something useful to add.

  14. #14
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    k.

    The function provided was javascript...

    I was trying to explain in my last paragraph that since the browser sees pages rendered by ASP.NET as nothing more than common XHTML/CSS/Javascript, nothing stops you from writing your own javascript and wiring it up exactly the same way as you normally would were you not working within a .NET environment.
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  15. #15
    Join Date
    Jun 2006
    Posts
    72
    [post broken into two due to max post length restrictions]

    I got everything working how i want it to now .

    Teddy, the javascript that you posted did not work for me. I think the problem was that it did not recognise "forms". What did work is below. I have to thank you nonetheless because your example was what I needed to get onto the right track.

    Code:
    <script type="text/jscript">
    <!--
        function SetRepGroup() 
        {
            myField = form1.elements("SelecedReportGroup");
            var e = document.getElementById("ddlistReportGroup"); // select element
            var myValue = e.options[e.selectedIndex].value
            myField.value = myValue
        }
    //-->
    </script>
    In case anyone reading this thread is interested, my code for the page_init is...

    Code:
        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            Dim i As Integer
            Dim SQL As String
            Dim sqlconn As New SqlConnection
    
            sqlconn.ConnectionString = SQLConnString
            sqlconn.Open()
    
            If IsPostBack Then
                SQL = "SELECT DISTINCT MethProdTechVerLists.MPTVID, Methods.ShortName, ProductsTested.ShortDesc AS ProdShort,  " _
                        + "Techniques.ShortDesc AS TechShort, ResultDetails.Version, MethProdTechVerLists.[Order] " _
                    + "FROM MethProdTechVerLists INNER JOIN " _
                          + "ResultDetails ON MethProdTechVerLists.MPTVID = ResultDetails.MPTVID INNER JOIN " _
                          + "Methods ON ResultDetails.MethodID = Methods.MethodID INNER JOIN " _
                          + "ProductsTested ON ResultDetails.ProductTested = ProductsTested.ProductTested INNER JOIN " _
                          + "Techniques ON ResultDetails.Technique = Techniques.Technique " _
                    + "WHERE MethProdTechVerLists.ReportGroupID='" + Request.Params("SelecedReportGroup") + "' " _
                    + "ORDER BY MethProdTechVerLists.[Order]"
                Dim sqlComm As New SqlCommand(SQL, sqlconn)
                Dim r As SqlDataReader = sqlComm.ExecuteReader()
    
                For i = 14 To gvTestGrid.Columns.Count - 1
                    gvTestGrid.Columns.Remove(gvTestGrid.Columns(14))
                Next
                i = 0
                While r.Read()
                    Dim MPTVID As Integer = CInt(r("MPTVID"))
                    Dim ShortMeth As String = r("ShortName")
                    Dim ShortProd As String = r("ProdShort")
                    Dim ShortTech As String = r("TechShort")
                    Dim ShortVer As String = r("Version")
    
                    Dim tf As New TemplateField()
    
                    Dim headerTemp As New MyHeaderTemplate()
                    headerTemp.HeadingText = ShortMeth + "<br />" + ShortProd + "<br />" + ShortTech + "<br />" + "Ver " + ShortVer
                    headerTemp.MPTVID = MPTVID
                    tf.HeaderTemplate = headerTemp
    
                    Dim itemTemp As New MyItemTemplate()
                    itemTemp.MPTVID = MPTVID
                    tf.ItemTemplate = itemTemp
    
                    tf.ItemStyle.Width = 4
    
                    gvTestGrid.Columns.Add(tf)
    
                    i += 1
                End While
            End If
        End Sub
    My code for the MyItemTemplate class is...

    Code:
    Imports System.Data.SqlClient
    Imports agric.wa.gov.au.AnnualDB.BusinessEntities
    Imports agric.wa.gov.au.AnnualDB.BusinessLogic
    Imports agric.wa.gov.au.AnnualDB.WebApp
    Imports System
    Imports System.Collections
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Web
    Imports System.Web.SessionState
    Imports System.Web.UI
    Imports System.Web.UI.WebControls.Button
    Imports System.Web.UI.HtmlControls
    Imports System.Text
    Imports System.Configuration
    Imports System.Configuration.ConfigurationManager
    
    Public Class MyItemTemplate
        Implements ITemplate
        'Expose the command event handler - when the command event handler is trapped internally this event is raised to inform the container 
        Public Event LinkButtonCommand As CommandEventHandler
        'Public Event LinkButtonClick As EventHandler 
        Private m_sMPTVID As String
    
        Public Property MPTVID() As String
            Get
                Return m_sMPTVID
            End Get
            Set(ByVal value As String)
                m_sMPTVID = value
            End Set
        End Property
    
        Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
            Dim text As New Label
            text.Style.Add("display", "block")
            'text.Style.Add("width", "4px")
            text.Style.Add("float", "left")
    
            AddHandler Text.DataBinding, AddressOf Me.BindText
            container.Controls.Add(Text)
    
    
            Dim lnkBtn As New LinkButton
            'lnkBtn.Style.Add("float", "left")
            AddHandler lnkBtn.DataBinding, AddressOf Me.BindLinkButtons
            'AddHandler lnkBtn.Click, New EventHandler(AddressOf Click)
            AddHandler lnkBtn.Command, New CommandEventHandler(AddressOf Command)
            container.Controls.Add(lnkBtn)
        End Sub
    
        Private Sub BindLinkButtons(ByVal sender As Object, ByVal e As EventArgs)
            Dim lnkBtn As LinkButton = CType(sender, LinkButton)
            Dim container As GridViewRow = CType(lnkBtn.NamingContainer, GridViewRow)
            'Dim cellContent As String = DataBinder.Eval(container.DataItem, "Content").ToString
            Dim cellContent As String = DataBinder.Eval(container.DataItem, MPTVID).ToString
            lnkBtn.Text = cellContent
            'lnkBtn.CommandName = MPTVID
            lnkBtn.CommandName = "ite" + DataBinder.Eval(container.DataItem, "SampleBarcode").ToString()
            lnkBtn.CommandArgument = "ite" + MPTVID
        End Sub
    
        Private Sub BindText(ByVal sender As Object, ByVal e As EventArgs)
            Dim txt As Label = CType(sender, Label)
            Dim row As GridViewRow = CType(txt.NamingContainer, GridViewRow)
            Dim cellContent As String = DataBinder.Eval(row.DataItem, MPTVID).ToString
            'txt.Text = MPTVID + ": "
        End Sub
    
        ''This will crash because the only event that's bubbled up is the Command Event....which takes a parameter of CommandEventArgs 
        'Private Sub Click(ByVal sender As Object, ByVal e As EventArgs) 
        '    RaiseEvent LinkButtonClick(Me, e) 
        'End Sub 
    
        'Handles the Command Event:  
        'When the link button is clicked the Command event is bubbled up to the container, which happens to be this class. 
        'This method bubbles the event up to the next level so that the event can be 
        'handled in the Page. 
        Private Sub Command(ByVal sender As Object, ByVal e As CommandEventArgs)
            RaiseEvent LinkButtonCommand(Me, e)
        End Sub
    
    End Class
    And my code for the MyHeaderTemplate class is...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •