Frinavale 9,735
Recognized Expert Moderator Expert
I have implemented the ITemplate interface to dynamically "display" complicated data in a GridView.
For the life of me I cannot implement the template in such a way that when it is applied to Header Data it is displayed as a link that raises a Sorting Event upon postback.
In my InstantiateIn method I create a LinkButton for my Header. I have added a handler to the LinkButton that calls a method upon DataBinding. In that method I have attempted everything I could possibly think of to get the LinkButton to cause a Sorting Event upon postback.
Has anyone done this?
I have a work around (that doesn't use a template for the Header) so there's is no urgency to this. I'm just dying to know how to get this to work.
Thanks
-Frinny
3 13995 Frinavale 9,735
Recognized Expert Moderator Expert
I went back to researching how to wire up dynamically created links/buttons in a template to click (command) events because I was never able to get this to work in the past.
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.
Another thing to note is that events are handled by the controls that they occur in. This means that you have to implement code that handles the event in your ITemplate class. If you want this to be handled in the Page that the template belongs to you will have to Bubble Up the event.
One last thing to note is that Click Events do not automatically bubble up for LinkButtons, Buttons and ImageButtons. Only the Command Event will bubble up.
The following is an example of some code that creates a template and bubbles up the Command Event of the link buttons in the template to the Page that the template belongs to: - Public Partial Class Practice
-
Inherits System.Web.UI.Page
-
Private _theSource As List(Of SomeClass)
-
-
Private Sub Practice_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
-
_theSource = New List(Of SomeClass)
-
_theSource.Add(New SomeClass("first", "data 1"))
-
_theSource.Add(New SomeClass("second", "data 2"))
-
_theSource.Add(New SomeClass("third", "data 3"))
-
_theSource.Add(New SomeClass("fourth", "data 4"))
-
Session("_theSource") = _theSource
-
-
'Please note that we are creating the GridView's Columns in the Page Init event.
-
'This is important because if you do not create the columns at this stage in the
-
'page life cycle the event for the dynamic link buttons will be lost!
-
-
Dim tf As New TemplateField
-
tf.HeaderText = "My Stuff"
-
-
'My Template is a Private Class that implements the ITemplate Field
-
'See it's definition farther down in the code.
-
Dim item As New MyTemplate()
-
-
'Assigning the function named "MyCommandHandlingFunction" to handle the templates LinkButtonCommand Event
-
AddHandler item.LinkButtonCommand, New CommandEventHandler(AddressOf MyCommandHandlingFunction)
-
-
'I was using the following in an attempt to bubble up the Click event for the
-
'Dynamic Link Button but this will never happen because I discovered that
-
'Only the Command Event will bubble up.
-
' AddHandler item.LinkButtonClick, New EventHandler(AddressOf MyCommandHandlingFunction)
-
-
-
'Adding the item to the template field
-
tf.ItemTemplate = item
-
-
'Creating the GridView's columns
-
myGrid.Columns.Add(tf)
-
-
End Sub
-
-
'This method simply binds the data source to the data grid
-
Private Sub DisplayGridView()
-
If _theSource Is Nothing Then
-
_theSource = Session("_theSource")
-
End If
-
myGrid.DataSource = _theSource
-
myGrid.DataBind()
-
End Sub
-
-
Private Sub Practice_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
-
DisplayGridView()
-
End Sub
-
-
'This method handles the Command Event that originates from the LinkButton
-
'In the Template
-
Private Sub MyCommandHandlingFunction(ByVal sender As Object, ByVal e As CommandEventArgs)
-
'e.CommandArgument contains "Sort"...we set this in the Template
-
End Sub
-
-
' Private Sub MyClickHandlingFunction(ByVal sender As Object, ByVal e As EventArgs)
-
'
-
' End Sub
-
-
-
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 = cellContent
-
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 = cellContent + ": "
-
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
-
-
-
-
'This class is used for the DataSource of the GridView
-
Private Class SomeClass
-
Private _title As String
-
Private _content As String
-
Public Property Title() As String
-
Get
-
Return _title
-
End Get
-
Set(ByVal value As String)
-
_title = value
-
End Set
-
End Property
-
Public Property Content() As String
-
Get
-
Return _content
-
End Get
-
Set(ByVal value As String)
-
_content = value
-
End Set
-
End Property
-
-
Public Sub New(ByVal theTitle As String, ByVal theContent As String)
-
_title = theTitle
-
_content = theContent
-
End Sub
-
End Class
-
-
-
End Class
The ASPX code for this page is: - <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Practice.aspx.vb" Inherits="ScratchPad.Practice" %>
-
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-
<html xmlns="http://www.w3.org/1999/xhtml" >
-
<head runat="server">
-
<title></title>
-
</head>
-
<body>
-
<form id="form1" runat="server">
-
<div>
-
<asp:GridView ID="myGrid" runat="server"
-
BorderColor="black"
-
GridLines="Horizontal"
-
BorderStyle="None"
-
allowpaging="True"
-
autogeneratecolumns="False"
-
style="margin-left:auto; margin-right:auto;"
-
width="200" EnableViewState="true"></asp:GridView>
-
</div>
-
</form>
-
</body>
-
</html>
Frinny,
I've been grappling with this problem for several days before locating your informative post. Not only did you provide a working example but your explanation of the problem allowed me to understand why my original attempts to handle such events were not working. Priceless.
I made one small deviation, I found that I had to add the gridview_RowCom mand event handler to process the commandName and commandArgument (and subsequent logic) passed by my link button.
My solution is within a visual web part but I'm not sure if this would account for the change.
Thanks again,
Jack
Frinavale 9,735
Recognized Expert Moderator Expert
I'm not sure why you had to make that change but I'm glad that my post helped you. I know I spent a lot of time trying to figure this stuff out :)
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: NateDawg |
last post by:
I'm reposting this. I'm kinda in a bind untill i get this figured out, so if
anyone has some input it would sure help me out.
Ok, I’ve noticed a few gridview problems floating around the forum. Everyone
wants to do a java confirmation box when a user clicks the delete button.
Fair enough, basic user design rules state that you should always confirm a
delete action. There is also a consensus that the best way to do this is a
template...
|
by: Tim_Mac |
last post by:
hi,
i'm new to .net 2.0, and am just starting to get to grips with the
gridview.
my page has autoEventWireUp set to true, which i gather is supposed to
figure out which handlers to invoke when appropriate based on your
method names .
the GridView has OnRowCommand="GridView1_RowCommand" in the aspx.
my problem is that the RowCommand event is firing twice (95% of the
time) on the page. the other 5% it only fires once. there's no
|
by: Miguel Dias Moura |
last post by:
Hello,
I have a GridView in my page which is created in runtime. It works fine.
My page has 2 Asp Buttons:
- The HIDE button makes GridView.Visible = False;
- The SHOW button makes GridView.Visible = True.
I press HIDE and the GridView disappears as expected.
After it I press SHOW and the GridView doesn't show.
|
by: J055 |
last post by:
Hi
I have a very simple configuration of the GridView with paging and sorting.
When I do a postback the DataBinding event fires twice - in both the
ProcessPostData and PreRender stages of the page life cycle.
In this example the event fires twice when a) GridView EnableViewState=False
and any image type control in the <columns/> element. When either
EnableViewState is set to true or the image button is removed, the event
fires once....
|
by: Rolf Barbakken |
last post by:
I have a most annoying problem:
I have a gridview with users from AD. When the user clicks on the header row
a postback is triggered, and the _Sorting-event fires. This is fine, and my
SortGrid-sub is called from there.
But the annoying part is that right after running through SortGrid the
_Sorting-event fires again. SortGrid sorts ASC/DESC alternating, and because
it fires twice every time, the gridview is obviously sorted the same...
| |
by: Kevin Attard |
last post by:
I am using a GridView inside a UserControl which has a template column for
deleting the rows. Before databinding the gridview i am attaching the
RowCommand and RowDataBound event.
I am using the RowDataBound event to set the commandargument of the delete
button. The event is being fired and works fine.
When I press the delete button, the RowCommand event is not firing! and
neither is the RowDeleting (the button's commandName is...
|
by: =?Utf-8?B?YmJkb2J1ZGR5?= |
last post by:
I have a question that maybe somebody can help me out.
I have a gridview that is bound to a sqltable, and I have created two
template columns.
I am having problems getting the sorting to work. I turned on the Allow
Sorting property but when I click one of the columns that is bound, it will
not sort.
Below is the code I am using
|
by: lilOlMe |
last post by:
Hi there!
I have generated a GridView that looks something like:
SportName| CompanyNameX |CompanyNameY |CompanyNameZ
Hockey.....| Shipping------------ |Accounting-------- |Shipping------------
BaseBall...| Receiving-----------|Shipping------------|Accounting---------
Etc............| Accounting----------|Receiving---------- |Receiving-----------
Where there are an unknown number of Company Names and an unknown number of Sport...
|
by: SAL |
last post by:
Hello,
I have a Gridview control (.net 2.0) that I'm having trouble getting the
Update button to fire any kind of event or preforming the update. The
datatable is based on a join so I don't know if that's what's causing the
behavior or not. It seems like the Update button should at least do
something.
When the Edit button is clicked, the grid goes into Edit mode and the Cancel
button takes the grid out of Edit mode. So, I don't get what...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |