Not able to click asp link button - asp.net

I have a linkbutton displaying the path of an uploaded document..The tag structure is like so
<tr>
<td>
<asp:Label ID="lblDoc" runat="server" Text="Document:"></asp:Label>
</td>
<td colspan="3">
<asp:LinkButton ID="lnkDoc" runat="server" PostBackUrl="~/Transfer.aspx"></asp:LinkButton>
</td>
</tr>
I am handling the onclick event on the server side:
Private Sub lnkDoc_Click(sender As Object, e As System.EventArgs) Handles lnkDoc.Click
ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('OpenDocument.aspx?DocumentPath=" & System.Web.HttpUtility.UrlEncode(lnkDoc.Text) & "', 'OpenUploadedDoc','left=0px,top=0px,width='+screen.availWidth+',height='+screen.availHeight+',menubar=yes,resizable=yes,scrollbars=1')</script>")
End Sub
But I am not able to click the document path. When I hover over the linkbutton, nothing happens. What could be the issue?
EDIT:
When I try to add onclick on the client side, I get the following error.
Transfer.Private Sub lnkDoc_Click(sender As Object, e As System.EventArgs)' is not accessible in this context because it is 'Private'.

I think there are some validation on your page so click event is not fire so please set causesvalidation="false" of LinkButton as below code and check again:
<asp:LinkButton ID="lnkDoc" causesvalidation="false" runat="server" PostBackUrl="~/Transfer.aspx"></asp:LinkButton
Thanks,
Hitesh

I have fixed the issue. The problem was with rendering the linkbutton in HTML(which was inside a panel). So I placed it in a outside the Panel.
</asp:Panel>
<div>
<asp:Label ID="lblDoc" style="margin-left: 3px" Text="Document: " runat="server"></asp:Label>
<asp:LinkButton ID="lnkDoc" style="margin-left:100px" runat="server" PostBackUrl="~/Transfer.aspx"></asp:LinkButton>
</div>
Thanks all for your suggestions..!

ASPX
<tr>
<td>
<asp:Label ID="lblDoc" runat="server" Text="Document:"></asp:Label>
</td>
<td colspan="3">
<asp:LinkButton ID="lnkDoc" CausesValidation="false" runat="server" Text="Test"></asp:LinkButton>
</td>
</tr>
Code behind
Private Sub lnkDoc_Click(sender As Object, e As System.EventArgs) Handles lnkDoc.Click
ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>alert('hi')</script>")
End Sub

try to give onclick event on .aspx page, and check it..
i hope that way it will work

Protected Sub lnkDoc_Click(sender As Object, e As System.EventArgs) Handles lnkDoc.Click
ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('OpenDocument.aspx?DocumentPath=" & System.Web.HttpUtility.UrlEncode(lnkDoc.Text) & "', 'OpenUploadedDoc','left=0px,top=0px,width='+screen.availWidth+',height='+screen.availHeight+',menubar=yes,resizable=yes,scrollbars=1')</script>")
End Sub
Note: make your event Protected not Private
And also You need to add the click event to link button.
<asp:LinkButton ID="lnkDoc" runat="server" PostBackUrl="~/Transfer.aspx" onclick="lnkDoc_Click"></asp:linkbutton>

Add text to the button and make the handler public.

You need to add the click event to link button.
<asp:LinkButton ID="lnkDoc" runat="server" onclick="lnkDoc_Click"></asp:linkbutton>
Page behind file you have to write
Protected Sub lnkDoc_Click((ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkDoc.Click
// code you want to run
End Sub

Maybe you want to set LinkButton.OnClientClick property? It let's you specify client-side handler for rendered link button control.
Take a look:
<asp:linkbutton id="LinkButton1" text="Open Web site" onclientclick="Navigate()" onclick="LinkButton1_Click" runat=Server />
Here Navigate() is a JavaScript function called upon click, and LinkButton1_Click is a server side event handler.
You want to open a new browser window to display a document when user clicks a link, right?
So a better approach will be to create JavaScript function with documentPath parameter (set on the server-side). No need to for messy RegisterStartupScript. You seem to run in circles now. Take a step back and rethink what you really want your code to do.

Related

Change image on button from aspx page

Below code for aspx file where able to get image .But when i tried to load image from code behind on button click it is not working
<asp:Image ID="imgCaptImg" runat="server" ImageUrl="~/Randomeimage.aspx" />
<asp:ImageButton ID="ButtonRefresh" runat="server" ImageUrl="~/Images/refreshimage.png" CausesValidation="False" />
<<"not working">>
Protected Sub ButtonRefresh_Click(sender As Object, e As ImageClickEventArgs) Handles ButtonRefresh.Click
imgCaptImg.ImageUrl = "~/Randomeimage.aspx"
End Sub

Server cannot set content type after HTTP headers have been sent - after error within an updatepanel

I'm getting the following error: Server cannot set content type after HTTP headers have been sent. I have looked around online, including some of the SO questions with exactly this error, but none have resolved my issue. Here is my particular scenario:
I have an asp.net gridview that is inside of an update panel (which also happens to be inside of a modalpopupextender). The gridview has a template field with an imagebutton that, when clicked, downloads a PDF. All works well until I run into an error trying to download. I handle the error inside the Gridview.RowCommand event, and the page doesn't change back on the client like I want. However, if I click the download again, the file doesn't download, and I catch the error inside ScriptManager.AsyncPostBackError event "Server cannot set content type after HTTP headers have been sent." Thanks in advance!
Here is my code:
--Default.aspx--
<asp:HiddenField ID="hdnHiddenField" runat="server" />
<cc1:ModalPopupExtender ID="hdnHiddenField_mpeModalPopup" runat="server" Enabled="True" TargetControlID="hdnHiddenField"
CancelControlID="lnkClose" PopupControlID="pnlPanel" BackgroundCssClass="modalBackground"></cc1:ModalPopupExtender>
<asp:Panel ID="pnlPanel" runat="server" BorderStyle="Double" Width="50%" Height="75%" CssClass="modalPopup" style="overflow: auto; display: none">
<div class="modalHeaderClose">
<asp:LinkButton ID="lnkClose" runat="server" Text="Close [X]"></asp:LinkButton>
</div>
<cc1:Accordion ID="accdnPolicyInfo" runat="server" SelectedIndex="0" RequireOpenedPane="false">
<Panes>
<cc1:AccordionPane ID="accpnlDocuments" runat="server">
<Header>
<div class="accordionHeader">Documents</div>
</Header>
<Content>
<asp:UpdatePanel ID="upDocuments" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div style="text-align: center; padding: 0 10px 10px 10px;">
<asp:GridView ID="gvGridView" runat="server" AutoGenerateColumns="False" Width="100%" ShowHeaderWhenEmpty="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgDownloadPDF" runat="server"
CommandArgument='<%# Bind("ImageKey") %>' CommandName="DownloadDocument"
ImageUrl="~/images/PDF-download.png" ToolTip="Download file to your computer" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle ForeColor="Red" HorizontalAlign="Center" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>
</asp:Panel>
--Default.aspx.vb--
Private Sub gvPolicyDocs_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPolicyDocs.RowDataBound
Dim imgDownloadPDF As ImageButton = e.Row.FindControl("imgDownloadPDF")
If imgDownloadPDF IsNot Nothing Then
ScriptManager.GetCurrent(Page).RegisterPostBackControl(imgDownloadPDF)
'I just tried changing to RegisterAsyncPostBackControl method and found that I receive the same error even on the first attempt
End If
End Sub
Protected Sub gvPolicyDocs_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvPolicyDocs.RowCommand
Try
StreamPDF(e.CommandArgument, False)
Catch ex As Exception
ErrorHandler.HandleError(ex) 'sends out an email and returns back; ErrorHandler is an object I created
End Try
hdnHiddenField_mpeModalPopup.Show() 'otherwise modal popup disappears after return from postback
End Sub
Private Sub StreamPDF(ByVal strImageKey As String)
Dim dtImagePaths As DataTable
Dim oPDFManager As New PdfManager 'from ASPPDF library
Dim bytes() As Byte
Dim strImagePath As String = String.Empty
If String.IsNullOrEmpty(strImageKey) Then
Throw New Exception("Invalid Image Key")
End If
'Get image path from database
...
...
strImagePath = dtImagePaths.Rows(0).Item("ImagePath")
bytes = oPDFManager.OpenDocument(strImagePath).SaveToMemory()
'I checked that on the run after the error, bytes contains exactly what I want - so when I write it to a file locally, I can see the PDF
With Current
.Response.BufferOutput = False 'tried true and false
.Response.Clear()
.Response.ClearContent()
.Response.ClearHeaders()
.Response.ContentType = "application/pdf"
.Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.pdf", IIf(bDownloadFile, "attachment", "inline"), strImageKey))
.Response.AddHeader("Content-Length", bytes.Length)
.Response.BinaryWrite(bytes)
.Response.Flush()
.Response.Close()
'Response.End() '--> See http://support.microsoft.com/kb/312629
.ApplicationInstance.CompleteRequest()
End With
End Sub
The UpdatePanel is probably the problem here.
Please see here.
Why won't Response.Write() export a CSV file to the browser?
Well, in case anyone else runs into this issue, this article helped me out completely. It basically indicates that you can't download and use the asyncpostback functionality (via UpdatePanel) on the same page. It demonstrates a workaround in which all of the download code is done on an entirely separate page, and that page is opened in a hidden iframe on the current page. On a side note, if you are also or instead trying to open the pdf in a new window, the same workaround applies but instead of adding an iframe to the current page, you can call window.open() in JavaScript.
So, I'm not sure how to fix this in VB, but I know the cause of this issue in C# as I have just had to deal with this issue myself.
The problem lies with the button itself. You need to register the button with the ScriptManager. You cannot do this at the PageLoad() event, you actually have to add an OnInit event to the button and add the registration there.
Example in C#:
ASP page code:
<asp:ImageButton ID="imgDownloadPDF" runat="server" onInit="imgDownloadPDF_Init" ... />
Code Behind:
protected void imgDownloadPDF_Init(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(imgDownloadPDF);
}
I hope this helps.

TextBox TextChange event is not working in vb.net

I am using asp textbox control with TextChange event, trying to set the text to label as the textbox text get changed but it is working when i loose the focus from textbox not when text changes.
the problem with loosing focus is that if i use AutoPostBack="true" it refresh the page which affects my other values...
my source for textbox on aspx page
<asp:TextBox ID="txtSearchCust" runat="server" Width = "200" OnTextChanged="txtSearchCust_TextChanged" AutoPostBack="true" />
my code behind page source
Protected Sub txtSearchCust_TextChanged(sender As Object, e As EventArgs) Handles txtSearchCust.TextChanged
QtyChk.Text=txtSearchCust.Text
End Sub
here QtyChk is the label where I am trying to set the text
any solution...?
Based on your question.
<script type="text/javascript">
function doTextBoxChange() {
__doPostBack();
}
</script>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" onkeydown="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack() Then
LabelChange()
End If
End Sub
Sub LabelChange()
Label1.Text = "1234"
End Sub
But I think use javascript is a better option.
The values will disappear after post, you need to request the value and setup.
otherwise, use viewstate or session.
Using the javascript, don't post form data.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
function doTextBoxChange() {
var inputValue = document.getElementById("TextBox1").value;
document.getElementById('<%= Label1.ClientID %>').innerHTML = inputValue;
}

UpdatePanel async postback not updating content

I have an issue very similar to this question. There is a dropdown on my page that causes a postback, during which the ImageUrl property of an ASP:Image is changed. When that postback happens, any value that is in the FileUpload is cleared. That's the problem I'm trying to solve, but I ran into this issue in the process.
I'm trying to solve the problem by wrapping the dropdown and image in an UpdatePanel. Here is my ASP markup:
<asp:UpdatePanel ID="upPanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myDropdown"
EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<tr valign="top">
<td>Tag:</td>
<td>
<asp:DropDownList ID="myDropdown" runat="server"
AppendDataBoundItems="true" DataTextField="Name"
DataValueField="ID" AutoPostBack="true">
<asp:ListItem Value="" />
</asp:DropDownList>
</td>
</tr>
<TR vAlign="top">
<TD width="150">Thumbnail:</TD>
<TD>
<asp:Image id="imgThumbnail" Runat="server"
AlternateText="No Image Found"
Visible="false"></asp:Image><BR>
</TD>
</TR>
</ContentTemplate>
</asp:UpdatePanel>
EDIT: my code-behind doing the update is here:
Private Sub myDropdown_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDropdown.SelectedIndexChanged
If (myDropdown.SelectedValue <> "-1") Then
imgThumbnail.ImageUrl = Application("AppPath") + "/Modules/Broadcaster/ImageGen.ashx?tag=" + myDropdown.SelectedValue
Else
imgThumbnail.ImageUrl = Application("AppPath") + "/Modules/Broadcaster/ImageGen.ashx?defaultTag=" + _modID.ToString()
End If
End Sub
I can see the async postback happening in FireBug, but the image URL does not change. What am I doing wrong?
You're missing the code that's doing the update (the code that is called by the selected index changing within the dropdown); however, I'm going to venture a guess that your problem is being caused because you are loading the DDL through a control instead of programmatically.
The reason you may be running into this issue is because the page load function is called before the datasource controls are populated, which means that the DDL is not populated by the time you are looking for a value, thus your image is coming up with a blank.
Example:
Dim sTemp As String = "images/myimagenumber" & myDropdown.SelectedIndex & ".jpg"
This will return "images/myimagenumber.jpg" as the value of the sTemp string because there is no value or index selected the the moment the page loads.
I suggest you load the values of the dropdownlist manually (programmatically) and then in the page_load subroutine make sure that it's only repopulating the dropdown when the page loads for the first time.
VB.Net Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Page.IsPostback = False Then
runDBLFillSubHere()
End If
'Run Rest of Code Here'
Sub
I've run into this a couple times over the years and it always ends up being because the DDL isn't populated before I am accessing it.

VB - how to link up a Check_change to code behind for a checkbox

How do I enable a check_change for a checkbox in VB.
Here is what I have so far.
Code Behind:
Protected Sub CheckBoxCash_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxCash.CheckedChanged
Label1.Text = "Cash"
End Sub
Front end code:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" />
It looks like you're not doing anything that specifically requires a postback here. In that case, I'd skip the postback entirely an do it more like this:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" onclick="document.getElementById('Label1').value = 'Cash';" />
Of course, that's the simple version. Production code would also involve checking the label's clientid property in case these controls ever end up inside a naming container (like an asp:panel or gridview). I'd also look for a fallback for when javascript is not enabled, but in this case the Check_Changed server event depends on javascript to fire anyway.
I figured it out, I forgot to set the postback to true

Resources