Solved

AddHandler for EditCommand of programatically created datagrid

Posted on 2004-09-10
17
420 Views
Last Modified: 2011-09-20
I'm creating datagrids programatically and I'm trying to add a handler for the EditCommand but the event never fires???

My code...

            Do While oDataReader4.Read()
                Dim litEnvironmentName As New System.Web.UI.WebControls.Literal
                Dim litRuleLine As New System.Web.UI.WebControls.Literal
                Dim colName As New System.Web.UI.WebControls.BoundColumn
                Dim colRole As New System.Web.UI.WebControls.BoundColumn
                Dim colEdit As New System.Web.UI.WebControls.EditCommandColumn

                EnvirID = oDataReader4("EnvironmentID")
                dvEnvPeopleRole.RowFilter = "EnvironmentID='" & EnvirID & "'"

                '** Create a datagrid for this Environment **
                Dim dgEnvironment As New System.Web.UI.WebControls.DataGrid
                dgEnvironment.ID = EnvirID
                dgEnvironment.EditItemStyle.Width = Unit.Percentage(95)
                dgEnvironment.EditItemStyle.BackColor = Color.FromArgb(255, 255, 204)
                dgEnvironment.ShowFooter = True
                dgEnvironment.AllowSorting = False
                dgEnvironment.AutoGenerateColumns = False
                dgEnvironment.BorderColor = Color.FromArgb(153, 153, 153)
                dgEnvironment.BorderStyle = BorderStyle.None
                dgEnvironment.BorderWidth = Unit.Pixel(1)
                dgEnvironment.BackColor = Color.White
                dgEnvironment.CellPadding = 3
                dgEnvironment.GridLines = GridLines.Vertical
                dgEnvironment.ItemStyle.BackColor = Color.FromArgb(238, 238, 238)
                dgEnvironment.ItemStyle.ForeColor = Color.Black
                dgEnvironment.HeaderStyle.Font.Bold = True
                dgEnvironment.HeaderStyle.ForeColor = Color.White
                dgEnvironment.HeaderStyle.BackColor = Color.FromArgb(0, 0, 132)
                dgEnvironment.AlternatingItemStyle.BackColor = Color.Gainsboro
                dgEnvironment.SelectedItemStyle.Font.Bold = True
                dgEnvironment.SelectedItemStyle.ForeColor = Color.White
                dgEnvironment.SelectedItemStyle.BackColor = Color.FromArgb(0, 138, 140)
                dgEnvironment.FooterStyle.ForeColor = Color.Black
                dgEnvironment.BackColor = Color.FromArgb(102, 204, 153)

                colName.DataField = "Name"
                colName.HeaderText = "Name"
                colRole.DataField = "RoleName"
                colRole.HeaderText = "Role"
                dgEnvironment.Columns.Add(colName)
                dgEnvironment.Columns.Add(colRole)
                colEdit.ButtonType = ButtonColumnType.PushButton
                colEdit.EditText = "Edit"
                colEdit.UpdateText = "Update"
                colEdit.CancelText = "Cancel"
                dgEnvironment.Columns.Add(colEdit)

                '** Add event handlers **
                AddHandler dgEnvironment.EditCommand, AddressOf dgEnvironment_Edit

                '** Bind the data to the datagrid **
                dgEnvironment.DataSource = dvEnvPeopleRole
                dgEnvironment.DataBind()

                litEnvironmentName.Text = "<h2>" & oDataReader4("EnvironmentName") & "</h2>"
                litRuleLine.Text = "<hr />"


                '** Add the Environment title and datagrid to the placeholder **
                phEnvironments.Controls.Add(litEnvironmentName)
                phEnvironments.Controls.Add(dgEnvironment)
                phEnvironments.Controls.Add(litRuleLine)

            Loop

    Sub dgEnvironment_Edit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

        '** Test that button click has been captured **
        litDebug.Text = "Edit button clicked!"

        BindData()
    End Sub
0
Comment
Question by:mattclip
  • 7
  • 6
  • 2
  • +1
17 Comments
 
LVL 10

Expert Comment

by:EBatista
ID: 12030387
try adding the handles in the event procedure:

Sub dgEnvironment_Edit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles dgEnvironment.EditCommand

        '** Test that button click has been captured **
        litDebug.Text = "Edit button clicked!"

        BindData()
End Sub
0
 

Author Comment

by:mattclip
ID: 12030440
I can't add the Handles to the event procedure because dgEnvironment has to be declared in the BindData() sub so that I can utilize the loop.
0
 
LVL 10

Expert Comment

by:EBatista
ID: 12031211
well, i dont see nothing wrong with your code...just put the AddHandler line after the binding ones for the datagrid.
0
 

Author Comment

by:mattclip
ID: 12031314
Same result.  Still not firing the event handler.  This one is driving me crazy!!
0
 
LVL 7

Expert Comment

by:jackiechen858
ID: 12034441
I created a test page to test your code, and it works fine.  can you add a breakpoint in the event function to make sure it's not fired? Maybe the binddata changed the litDebug.text back?  and since the datagrids are created dynamicly, you must create them everytime, not only the first time (not ispostback ).


Public Class testcode
    Inherits System.Web.UI.Page
    Protected WithEvents litDebug As System.Web.UI.WebControls.Label
    Protected WithEvents phEnvironments As System.Web.UI.WebControls.PlaceHolder

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Private Sub loaddata(ByVal EnvironmentID As String)

        Dim dt As DataTable = New DataTable()
        Dim dc As DataColumn = New DataColumn("Name")
        dt.Columns.Add(dc)
        dc = New DataColumn("RoleName")
        dt.Columns.Add(dc)

        Dim dr As DataRow = dt.NewRow()
        dr(0) = "jack"
        dr(1) = "Admin"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr(0) = "tom"
        dr(1) = "Admin"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr(0) = "mary"
        dr(1) = "user"
        dt.Rows.Add(dr)

        Dim litEnvironmentName As New System.Web.UI.WebControls.Literal()
        Dim litRuleLine As New System.Web.UI.WebControls.Literal()
        Dim colName As New System.Web.UI.WebControls.BoundColumn()
        Dim colRole As New System.Web.UI.WebControls.BoundColumn()
        Dim colEdit As New System.Web.UI.WebControls.EditCommandColumn()

        Dim EnvirID As String = EnvironmentID
        'dvEnvPeopleRole.RowFilter = "EnvironmentID='" & EnvirID & "'"

        '** Create a datagrid for this Environment **
        Dim dgEnvironment As New System.Web.UI.WebControls.DataGrid()
        dgEnvironment.ID = EnvirID
        dgEnvironment.EditItemStyle.Width = Unit.Percentage(95)
        dgEnvironment.EditItemStyle.BackColor = Color.FromArgb(255, 255, 204)
        dgEnvironment.ShowFooter = True
        dgEnvironment.AllowSorting = False
        dgEnvironment.AutoGenerateColumns = False
        dgEnvironment.BorderColor = Color.FromArgb(153, 153, 153)
        dgEnvironment.BorderStyle = BorderStyle.None
        dgEnvironment.BorderWidth = Unit.Pixel(1)
        dgEnvironment.BackColor = Color.White
        dgEnvironment.CellPadding = 3
        dgEnvironment.GridLines = GridLines.Vertical
        dgEnvironment.ItemStyle.BackColor = Color.FromArgb(238, 238, 238)
        dgEnvironment.ItemStyle.ForeColor = Color.Black
        dgEnvironment.HeaderStyle.Font.Bold = True
        dgEnvironment.HeaderStyle.ForeColor = Color.White
        dgEnvironment.HeaderStyle.BackColor = Color.FromArgb(0, 0, 132)
        dgEnvironment.AlternatingItemStyle.BackColor = Color.Gainsboro
        dgEnvironment.SelectedItemStyle.Font.Bold = True
        dgEnvironment.SelectedItemStyle.ForeColor = Color.White
        dgEnvironment.SelectedItemStyle.BackColor = Color.FromArgb(0, 138, 140)
        dgEnvironment.FooterStyle.ForeColor = Color.Black
        dgEnvironment.BackColor = Color.FromArgb(102, 204, 153)

        colName.DataField = "Name"
        colName.HeaderText = "Name"
        colRole.DataField = "RoleName"
        colRole.HeaderText = "Role"
        dgEnvironment.Columns.Add(colName)
        dgEnvironment.Columns.Add(colRole)
        colEdit.ButtonType = ButtonColumnType.PushButton
        colEdit.EditText = "Edit"
        colEdit.UpdateText = "Update"
        colEdit.CancelText = "Cancel"
        dgEnvironment.Columns.Add(colEdit)

        '** Add event handlers **
        AddHandler dgEnvironment.EditCommand, AddressOf dgEnvironment_Edit

        '** Bind the data to the datagrid **
        dgEnvironment.DataSource = dt
        dgEnvironment.DataBind()

        litEnvironmentName.Text = "<h2>" & "EnvironmentName" & "</h2>"
        litRuleLine.Text = "<hr />"

        '** Add the Environment title and datagrid to the placeholder **
        phEnvironments.Controls.Add(litEnvironmentName)
        phEnvironments.Controls.Add(dgEnvironment)
        phEnvironments.Controls.Add(litRuleLine)

    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        'If Not Page.IsPostBack Then
        loaddata("A")
        loaddata("B")

        'End If

    End Sub


    Sub dgEnvironment_Edit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

        '** Test that button click has been captured **
        litDebug.Text = "Edit button clicked!"
        'BindData()
    End Sub
End Class
0
 

Author Comment

by:mattclip
ID: 12035625
I don't have time to check this now as I am getting on a plane for a week long business trip, but thanks for the feedback and I'll let you know how it turns out when I get back.
0
 
LVL 1

Expert Comment

by:keijerjh
ID: 12036421
Hi,

You should set the CommandName of the button to 'Edit'.
This should fire the event Editcommand.

Greetings,
Jelle
0
 
LVL 1

Expert Comment

by:keijerjh
ID: 12097465
Hi Matt,

Any progress?
I've had the same problem and my comment above solved the problem.
The datagrid raises the EditCommand event based upon the CommandName of a Button/LinkButton.

Greetings,
Yelle
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:mattclip
ID: 12103412
Ok I appear to be closer now.  The problem was my BindData sub wasn't being called on the post back because I had it in the If Not Page.IsPostBack block.  The litDebug is being populated now when I click on the edit button.

Now how do I set the item the user selected to edit?  Normally I would just do... datagridName.EditItemIndex...but in this case the datagrid names are created dynamcially so what is the syntax in this case?

Thanks,
Matt
0
 
LVL 7

Expert Comment

by:jackiechen858
ID: 12103473
it should be the sender.

 Sub dgEnvironment_Edit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

        '** Test that button click has been captured **
        litDebug.Text = "Edit button clicked!"
        'BindData()
        dim dg as DataGrid dg = CType( sender, DataGrid )
    End Sub

0
 

Author Comment

by:mattclip
ID: 12103808
Ok I added this...
        Dim dgThis As DataGrid = CType(sender, DataGrid)
        '** Set the item the user selected to edit **
        dgThis.EditItemIndex = e.Item.ItemIndex
        dgThis.ShowFooter = "false"

The footer is no longer displayed after I click on the Edit button of EditCommandColumn but the row does not change to an editable row?  The update and cancel buttons don't appear?  The column still contains the edit button?  I did add the e.Item.ItemIndex to the litDebug so I know the correct integer is being passed.

Thanks,
Matt
0
 
LVL 7

Expert Comment

by:jackiechen858
ID: 12104089
you need to rebind the data after dgThis.EditItemIndex = e.Item.ItemIndex
0
 

Author Comment

by:mattclip
ID: 12105442
I tried calling my sub that binds the data to rebind the data the problem but it does not work??
0
 
LVL 7

Expert Comment

by:jackiechen858
ID: 12105517
After I tried the sample code, I found a really weird problem, the  e.Item.ItemIndex can only increase, not decrease.

I read the article
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/aspnet-commondatagridmistakes.asp
, and reallise maybe the problem is still in isPostBack. I modified the code, now it works as expected.

I have 2 precedures, CreateDataGrid only create datagrid, BindData add rows to datagrid.

in Page_Load, CreateDataGird must be called, but BindData only be called if not IsPostBack

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        CreateDataGrid("A")
        CreateDataGrid("B")
        If Not IsPostBack Then
            Dim dgthis As DataGrid = CType(Me.FindControl("A"), DataGrid)
            Me.BindData(dgthis)
            dgthis = CType(Me.FindControl("B"), DataGrid)
            Me.BindData(dgthis)
        End If
    End Sub




    Private Sub BindData(ByRef dg As DataGrid)
        Dim dt As DataTable = New DataTable()
        Dim dc As DataColumn = New DataColumn("Name")
        dt.Columns.Add(dc)
        dc = New DataColumn("RoleName")
        dt.Columns.Add(dc)

        Dim dr As DataRow = dt.NewRow()
        dr(0) = "jack"
        dr(1) = "Admin"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr(0) = "tom"
        dr(1) = "Admin"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr(0) = "mary"
        dr(1) = "user"
        dt.Rows.Add(dr)

        dg.DataSource = dt
        dg.DataBind()
    End Sub

    Private Sub CreateDataGrid(ByVal EnvironmentID As String)
        Dim litEnvironmentName As New System.Web.UI.WebControls.Literal()
        Dim litRuleLine As New System.Web.UI.WebControls.Literal()
        Dim colName As New System.Web.UI.WebControls.BoundColumn()
        Dim colRole As New System.Web.UI.WebControls.BoundColumn()
        Dim colEdit As New System.Web.UI.WebControls.EditCommandColumn()

        Dim EnvirID As String = EnvironmentID
        'dvEnvPeopleRole.RowFilter = "EnvironmentID='" & EnvirID & "'"

        '** Create a datagrid for this Environment **
        Dim dgEnvironment As New System.Web.UI.WebControls.DataGrid()
        dgEnvironment.ID = EnvirID
        dgEnvironment.EditItemStyle.Width = Unit.Percentage(95)
        dgEnvironment.EditItemStyle.BackColor = Color.FromArgb(255, 255, 204)
        dgEnvironment.ShowFooter = True
        dgEnvironment.AllowSorting = False
        dgEnvironment.AutoGenerateColumns = False
        dgEnvironment.BorderColor = Color.FromArgb(153, 153, 153)
        dgEnvironment.BorderStyle = BorderStyle.None
        dgEnvironment.BorderWidth = Unit.Pixel(1)
        dgEnvironment.BackColor = Color.White
        dgEnvironment.CellPadding = 3
        dgEnvironment.GridLines = GridLines.Vertical
        dgEnvironment.ItemStyle.BackColor = Color.FromArgb(238, 238, 238)
        dgEnvironment.ItemStyle.ForeColor = Color.Black
        dgEnvironment.HeaderStyle.Font.Bold = True
        dgEnvironment.HeaderStyle.ForeColor = Color.White
        dgEnvironment.HeaderStyle.BackColor = Color.FromArgb(0, 0, 132)
        dgEnvironment.AlternatingItemStyle.BackColor = Color.Gainsboro
        dgEnvironment.SelectedItemStyle.Font.Bold = True
        dgEnvironment.SelectedItemStyle.ForeColor = Color.White
        dgEnvironment.SelectedItemStyle.BackColor = Color.FromArgb(0, 138, 140)
        dgEnvironment.FooterStyle.ForeColor = Color.Black
        dgEnvironment.BackColor = Color.FromArgb(102, 204, 153)

        colName.DataField = "Name"
        colName.HeaderText = "Name"
        colRole.DataField = "RoleName"
        colRole.HeaderText = "Role"
        dgEnvironment.Columns.Add(colName)
        dgEnvironment.Columns.Add(colRole)
        colEdit.ButtonType = ButtonColumnType.PushButton
        colEdit.EditText = "Edit"
        colEdit.UpdateText = "Update"
        colEdit.CancelText = "Cancel"
        dgEnvironment.Columns.Add(colEdit)

        '** Add event handlers **
        AddHandler dgEnvironment.EditCommand, AddressOf dgEnvironment_Edit

        '** Bind the data to the datagrid **
        litEnvironmentName.Text = "<h2>" & "EnvironmentName" & "</h2>"
        litRuleLine.Text = "<hr />"

        '** Add the Environment title and datagrid to the placeholder **
        phEnvironments.Controls.Add(litEnvironmentName)
        phEnvironments.Controls.Add(dgEnvironment)
        phEnvironments.Controls.Add(litRuleLine)
    End Sub

    Sub dgEnvironment_Edit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Dim dgThis As DataGrid = CType(sender, DataGrid)
        '** Set the item the user selected to edit **

        '** Test that button click has been captured **
        litDebug.Text = dgThis.ID & "Edit button clicked!"
        dgThis.EditItemIndex = e.Item.ItemIndex
        Me.BindData(dgThis)
    End Sub


0
 

Author Comment

by:mattclip
ID: 12106714
THAT DID IT!!! THANKS SO MUCH!!!
0
 
LVL 7

Accepted Solution

by:
jackiechen858 earned 500 total points
ID: 12106968
You are welcome:-) I also cleared my thought about postback.
0
 
LVL 7

Expert Comment

by:jackiechen858
ID: 12111412
Hi mattclip,

Could you accept my answer now? I need one more answered question to get my free premium service :-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now