C# code not firing when link or button is clicked

I have tried multiple methods and I cannot figure out why this code will not fire.

Page code:

<asp:Button id="deleteLink" runat="server" text='delete'
                                                            oncommand="deleteLink_Command" commandargument='<%# Eval("AttachmentId") %>' />


Any help would be appreciated!

-D-
//code behind code

protected void deleteLink_Command(object sender, CommandEventArgs e)
   {
      int attachId = int.Parse(e.CommandArgument.ToString());
     Attachment attach = new Attachment();
     attach.InitByPK(attachId);
     attach.Delete();
     this.Messages.Add(new SuccessMessage("Attachment has been deleted"));
     Response.Redirect(Request.Url.ToString());
 }

Open in new window

LVL 18
John Gates, CISSPSecurity ProfessionalAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
John Gates, CISSPConnect With a Mentor Security ProfessionalAuthor Commented:
This one will haunt me for some time....  Here is the solution:

<asp:LinkButton id="deleteLink" runat="server" text='delete' causesvalidation="false"
oncommand="deleteLink_Command" commandargument='<%# Eval("AttachmentId") %>' />


It required the causesvalidation to be set to false.  After I did this the page worked and the code halted on my breakpoint as expected.

Glad it's over!

-D-
0
 
JosephEricDavisCommented:
I'm guessing that this link button exists inside of a gridview control...

If this is the case than you don't need to wire up the oncommand event like you are.  Your link button can just look something like this...

<asp:LinkButton runat="server" ID="lbDelete" Text="Delete" CommandName="Delete" CommandArgument='<%# Eval("AttachmentId")%>' />

Then in your code behind you would do this...

protected void gvYourGridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        //Code you want to execute on Delete
        //You can access the id of the AttachmentId like this...
        Int32 AttachmentId = Convert.ToInt32(e.CommandArgument);
    }
}
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
Here is the complete aspx snippet:

<asp:Repeater runat="server" id="attachmentRepeater" datasource="<%# Attachments %>">
                                    <itemtemplate>
                                          <tr>
                                                <td style="padding-right:30px">
                                                      <asp:HyperLink id="attachmentDownloadLink" runat="server"
                                                            navigateurl='<%# Eval("VirtualPath").ToString() + Eval("FileName").ToString() %>'
                                                            target="_blank"
                                                            ><img runat="server" src="~/images/attach.gif" border="0" align="absmiddle" alt="" /><%# Eval("AttachmentName") %></asp:HyperLink>
                                                </td>
                                                <td style="padding-right:30px">
                                                      <%# Eval("FileName") %>
                                                </td>
                                                <td style="padding-right:30px" align="right">
                                                      <%# Eval("DisplaySize") %>
                                                </td>
                                                <td style="padding-right:30px">
                                                      <%# ((Attachment) Container.DataItem).CreatedDate.GetValue("d-MMM-yy") %>
                                                </td>
                                                <td runat="server" visible="<%# CmsUser.CanModifyAttachments(Course.DepartmentId.ValueInt) %>">
                                                      <asp:HyperLink id="editLink" runat="server" text="edit"
                                                            navigateurl='<%# Request.Path + "?unitId=" + UnitId + "&attachId=" + Eval("AttachmentId") %>' />
                                                       |
                                                      <asp:linkButton id="deleteLink" runat="server" text='delete'
                                                            oncommand="deleteLink_Command" commandargument='<%# Eval("AttachmentId") %>' CommandName="deleteLink" EnableViewState="False" />
                                                </td>
                                          </tr>
                                    </itemtemplate>
                              </asp:Repeater>    

The item is in a repeater not a datagrid.  Is there a method in this case?

-D-
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
JosephEricDavisCommented:
If you aren't operating within the bounds of a gridview control then you are probably making this harder than it needs to be in the way that you are going about it.  If you could post some of your code and describe your situation a little more I could probably help you a bit further.
0
 
JosephEricDavisCommented:
<asp:Repeater runat="server" ID="attachmentRepeater" OnItemCommand="attachmentRepeater_OnItemCommand">
    </asp:Repeater>

protected void attachmentRepeater_OnItemCommand(object sender, RepeaterCommandEventArgs e)
        {
        }


Refer to my previous code example in using the gridview, but substitute this markup and method signature.
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
I have tried the above to no avail...  No matter what code is placed when the button is hovered over this is what it is referring to..:

javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("_ctl0:_ctl0:_ctl0:mainContent:centerContent:centerContent:attachmentRepeater:_ctl0:deleteLink", "", true, "", "", false, true))


P.S.  I inherited this fine project after 4 other developers that worked on it and never documented anything have had their way with it.  I am just trying to make sense of this.  VB.NET is the language I am most familiar with.  I have never seen an event not fire like this.  I will post the entire page and code behind code.  I just want this to work :-)

Thanks
-D-

<ASPX page>

<%@ Page Language="C#" MasterPageFile="~/Secure/Courses/CourseConsoleMaster.master" AutoEventWireup="true" CodeFile="CourseUnitAttachment.aspx.cs" Inherits="Secure_Courses_CourseUnitAttachment" %>
<%@ Import namespace="CMS.Data.Entities" %>

<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="leftContent">
    <uc:CourseList Runat="server" ID="CourseList"/>
</asp:Content>

<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="centerContent">
    <table width="100%">
		<tr>
			<td class="tabSelected" style="padding: 10px">

				<div id="consolecrumb">
					<asp:HyperLink runat="server" NavigateUrl='<%# "CourseUnits.aspx?grade=" + GradeCode + "&course=" + CourseId %>'
						Text='<%# Unit.UnitName + "&gt; Attachments" %>' />  
				</div>

				<uc:Messages runat="server" />
				
				<table>
					<tr runat="server" visible="<%# Attachments.Count == 0 %>">
						<td>
							There are no existing attachments.
						</td>
					</tr>
					<asp:Repeater runat="server" id="attachmentRepeater" datasource="<%# Attachments %>">
						<itemtemplate>
							<tr>
								<td style="padding-right:30px">
									<asp:HyperLink id="attachmentDownloadLink" runat="server"
										navigateurl='<%# Eval("VirtualPath").ToString() + Eval("FileName").ToString() %>'
										target="_blank" 
										><img runat="server" src="~/images/attach.gif" border="0" align="absmiddle" alt="" /><%# Eval("AttachmentName") %></asp:HyperLink>
								</td>
								<td style="padding-right:30px">
									<%# Eval("FileName") %>
								</td>
								<td style="padding-right:30px" align="right">
									<%# Eval("DisplaySize") %>
								</td>
								<td style="padding-right:30px">
									<%# ((Attachment) Container.DataItem).CreatedDate.GetValue("d-MMM-yy") %>
								</td>
								<td runat="server" visible="<%# CmsUser.CanModifyAttachments(Course.DepartmentId.ValueInt) %>">
									<asp:HyperLink id="editLink" runat="server" text="edit" 
										navigateurl='<%# Request.Path + "?unitId=" + UnitId + "&attachId=" + Eval("AttachmentId") %>' />
									 | 
									<asp:linkButton id="deleteLink" runat="server" text='delete' 
										commandargument='<%# Eval("AttachmentId") %>' CommandName="Delete" EnableViewState="False" /> 
								</td>
							</tr>
						</itemtemplate>
					</asp:Repeater>     
				</table>
				<hr />
				<table runat="server" visible="<%# CmsUser.CanModifyAttachments(Course.DepartmentId.ValueInt) %>">
					<tr>
						<td colspan="2">
							<b>Add Attachment</b> <br /> <br />
						</td>
					</tr>
					<tr>
						<td>
							Attachment Name:
						</td>
						<td>
							<dk:LabelTextBox ID="attachmentNameTextBox" Columns="30" runat="server" 
								Text="<%# Attach.AttachmentName %>" MaxLength="50" />
							<dk:Validator runat="server" Required="true" Label="Attachment Name"
								Control="attachmentNameTextBox" />
							<dk:FocusSetter runat="server" Control="attachmentNameTextBox" />
						</td>
					</tr>
					<tr runat="server" visible="<%# Attach.IsNew %>">
						<td>
							File Path:
						</td>
						<td>
							<input type="file" runat="server" id="uploadFile" name="uploadFile" />
							<dk:Validator runat="server" Control="uploadFile" Label="File Path"
								Required="true" />
						</td>
					</tr>
					<tr>
						<td></td>
						<td>
							<br />
							<asp:Button runat="server" text="Submit" onclick="uploadButton_Click" id="Button1" />
							<asp:Button runat="server" text="Cancel" onclick="cancelButton_Click" id="Button2" />
						</td>
					</tr>
				</table>
			</td>
		</tr>
	</table>
	<br />
</asp:Content>


</Page>

</page code>

<Code behind>
using System;
using System.Collections;
using System.Web.UI.WebControls;
using CMS.Data.Entities;
using CMSWeb.Public;
using DK.Util;
using DK.Web;

public partial class Secure_Courses_CourseUnitAttachment : BasePage
{
    private IList _attachments;
    private Attachment _attachment;
     
    public override void DataBind()
    {
        Page.Items["ConsoleTab"] = "units";
        base.DataBind();
    }
    
    protected IList Attachments
    {
        get
        {
            if (_attachments == null)
            {   
                Attachment a = new Attachment();
                _attachments = a.FindByUnitOfStudyId(UnitId);
            }
            return _attachments;
        }

    }
    
    protected Attachment Attach
    {
        get
        {
            if (_attachment == null)
            {
                _attachment = new Attachment();
                if (AttachmentId > 0)
                {
                    _attachment.InitByPK(AttachmentId);
                }
            }
            return _attachment;
        }
    }
    
//    protected void attachClick_Command(object sender, EventArgs e)
//    {
//        Response.Redirect("~/Secure/Courses/CourseUnitAttachment.aspx" + "?unitId=" + UnitId);// + "?attachmentId=" + AttachmentId);
//    }

    protected void attachmentRepeater_OnItemCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            int attachId = int.Parse(e.CommandArgument.ToString());
            Attachment attach = new Attachment();
            attach.InitByPK(attachId);
            attach.Delete();
            this.Messages.Add(new SuccessMessage("Attachment has been deleted"));
            Response.Redirect(Request.Url.ToString());
        }
    }



 protected void deleteLink_Command(object sender, CommandEventArgs e)
   {
      int attachId = int.Parse(e.CommandArgument.ToString());
     Attachment attach = new Attachment();
     attach.InitByPK(attachId);
     attach.Delete();
     this.Messages.Add(new SuccessMessage("Attachment has been deleted"));
     Response.Redirect(Request.Url.ToString());
 }

    protected void UploadFile()
    {
        Attach.AttachmentName.Value = attachmentNameTextBox.Text.Trim();
        if (Attach.IsNew)
        {
            Attach.PostedFile = uploadFile.PostedFile;
            Attach.UnitOfStudyId.ValueInt = UnitId;
            // set schoolId and courseId to determine file location for new attachments
            Attach.SchoolId.ValueInt = CmsSession.SchoolId;
            Attach.CourseId.ValueInt = CourseId;
        }
        Attach.Save(CmsSession.UserId);
    }

    protected void uploadButton_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            UploadFile();
            Messages.Add(new SuccessMessage("Attachment saved successfully"));
            Response.Redirect(Request.Url.ToString());
        }
    }

    protected void cancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(Url("~/Secure/Courses/CourseUnits.aspx?dept&grade&course"));
    }
    
    protected int AttachmentId
    {
        get
        {
            if (StringUtil.HasChars(Request["attachId"]))
            {
                return int.Parse(Request["attachId"]);
            }
            else
            {
                return 0;
            }
        }
    }
}

</Code behind>

Open in new window

0
 
JosephEricDavisCommented:
It looks like you forgot to add the

OnItemCommand="attachmentRepeater_OnItemCommand"

to the markup of the repeater like I showed in my example...

So you placed the method in the code behind, but you never actually wired it up to an event.
0
 
JosephEricDavisCommented:
So...

<asp:Repeater runat="server" id="attachmentRepeater" datasource="<%# Attachments %>" OnItemCommand="attachmentRepeater_OnItemCommand">
     <itemtemplate>
          <tr>
.....
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
the same result occurs.  When hovering over the button the following is displayed:

javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("_ctl0:_ctl0:_ctl0:mainContent:centerContent:centerContent:attachmentRepeater:_ctl0:deleteLink", "", true, "", "", false, true))

I just don't get it.
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
You click and nothing happens.  I am attaching the code again so that you see the changes..  I have a breakpoint set in the code and it never catches.  The attachmentRepeater_OnItemCommand event never gets called.  I have never seen anything like it.


-D-
<asp:Repeater runat="server" id="attachmentRepeater" datasource="<%# Attachments %>" OnItemCommand="attachmentRepeater_OnItemCommand">
						<itemtemplate>
							<tr>
								<td style="padding-right:30px">
									<asp:HyperLink id="attachmentDownloadLink" runat="server"
										navigateurl='<%# Eval("VirtualPath").ToString() + Eval("FileName").ToString() %>'
										target="_blank" 
										><img runat="server" src="~/images/attach.gif" border="0" align="absmiddle" alt="" /><%# Eval("AttachmentName") %></asp:HyperLink>
								</td>
								<td style="padding-right:30px">
									<%# Eval("FileName") %>
								</td>
								<td style="padding-right:30px" align="right">
									<%# Eval("DisplaySize") %>
								</td>
								<td style="padding-right:30px">
									<%# ((Attachment) Container.DataItem).CreatedDate.GetValue("d-MMM-yy") %>
								</td>
								<td runat="server" visible="<%# CmsUser.CanModifyAttachments(Course.DepartmentId.ValueInt) %>">
									<asp:HyperLink id="editLink" runat="server" text="edit" 
										navigateurl='<%# Request.Path + "?unitId=" + UnitId + "&attachId=" + Eval("AttachmentId") %>' />
									 | 
									<asp:linkButton id="deleteLink" runat="server" text='delete' 
										commandargument='<%# Eval("AttachmentId") %>' CommandName="Delete" EnableViewState="False" /> 
								</td>
							</tr>
						</itemtemplate>
					</asp:Repeater>     



<----------code behind start -------------------->


   protected void attachmentRepeater_OnItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            int attachId = int.Parse(e.CommandArgument.ToString());
            Attachment attach = new Attachment();
            attach.InitByPK(attachId);
            attach.Delete();
            this.Messages.Add(new SuccessMessage("Attachment has been deleted"));
            Response.Redirect(Request.Url.ToString());
        }
    }

Open in new window

0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
Ideas?
0
 
JosephEricDavisCommented:
If you comment out the attachmentRepeater_OnItemCommand method in the code behind and run the application, when you go to the page does it throw and error?

Whenever you refer to a method as an event in the markup of the aspx page, if that method does not exist in the code behind it should throw an error.

Is this even happening?
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
It does throw an error even before it runs.  So that part is happening...  Just for some reason it is not calling it when the linkbutton is clicked.
0
 
JosephEricDavisCommented:
Geese... I'm not sure.

It may be time for you to change strategies.  All you need is for link button to delete the data row in the repeater?

You may try using a plain old HTML anchor tag that calls a JavaScript function which will do an asynchronous request out to your sever to delete the database record.

Is this a feasible solution?  Let me know if you need help implementing.
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
Not really.  I am not in love with C# at all at this point....  There are other methods that get produced with that repeater that call a link or URL and they parse fine...  I really want to find out why this linkbutton is not functioning as expected.

-D-
0
 
JosephEricDavisCommented:
I'm afraid I'm out of ideas for you.
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
Thanks for trying.

-D-
0
 
John Gates, CISSPSecurity ProfessionalAuthor Commented:
I found the solution on my own.
0
All Courses

From novice to tech pro — start learning today.