LinkButton not rendered completely - asp.net

I have this function that I call in page int event
Protected Function RenderLB(text As String, Id As String, argument As String) As [String]
Using Lb = New System.Web.UI.WebControls.LinkButton
Lb.Text = text
Lb.ID = Id
Lb.Attributes.Add("runat", "Server")
Lb.CommandName = "RedirectFillsession"
Lb.CommandArgument = argument
Dim StringBuilder = New System.Text.StringBuilder()
Using stringWriter = New System.IO.StringWriter(StringBuilder)
Using htmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWriter)
Lb.RenderControl(htmlTextWriter)
End Using
End Using
Return StringBuilder.ToString()
End Using
End Function
the returned value is anchor but CommandName and CommandArgument are not rendered
what should I do to render the CommandName and CommandArgument

CommandName and CommandArgument are never rendered into the output HTML, they are used in the accompanying JavaScript.
Also, you should add your control to the controls collection instead of rendering it manually. That way you can be sure its part of the entire Page Life Cycle.
Controls.Add(Lb)

Related

How can I add a hyperlink to a dropdownlist create in vb.net code behind?

I create a dropdownlist in code behind with this:
Public sub CreateDDL()
Dim ddl As New DropDownList
Dim list As ListItem = New ListItem()
list.Text = "printTemplate1"
list.value = "~/template1.aspx"
ddl.Items.Add(list)
End Sub
I don't know how to put the value to be a link.
Suggest me, thanks.
I solve my problem at this way :
Public sub CreateDDL()
Dim ddl As New DropDownList
' ############# THE MODIFICATION ########################
ddl.Attributes.Add("onchange", "template1.aspx")
' ##################################################
Dim list As ListItem = New ListItem()
list.Text = "printTemplate1"
ddl.Items.Add(list)
End Sub
I hope it will be helpful to someone
What you are looking for is quite not possible because DropDownList render themselves into native HTML select. These controls aren't really designed to do such kind of activity.
In order to make them navigate to other page you need to combine them with client side script and make them behave as per your requirement. For E.g.
$(function() {
$("#<%=ddl.ClientID%>").change(function(e) {
var selectedUrl = $(this).val();
window.location.href = selectedUrl;
});
});
Also you can make use of ResolveURL() or ResolveClientUrl() to create a relative path to the root or relative to the current page respectively and then assign them to the ddl value.
list.value = ResolveUrl("~/template1.aspx");
/*or*/
list.value = ResolveClientUrl("~/template1.aspx");

Creating a New control of the same type as another control that is already declared

I'm using a custom template class to generate lines with my repeater control, i'd like to be able to specify the controls in this repeater dynamically from the code behind my aspx page.
In the code behind I've added controls to a list like this:
Dim lstControls As New List(Of Control)
lstControls.Add(New TextBox)
lstControls.Add(New Label)
lstControls.Add(New CheckBox)
lstControls.Add(New DropDownList)
lstControls.Add(New CheckBox)
Then i use this line to add the controls to my template
rptrSummary.ItemTemplate = New myTemplate(ListItemType.Item, , lstControls)
From the instantiateIn sub i'm doing something like this:
Dim ph As New PlaceHolder
For i = 0 To lstControls.Count - 1
ph.Controls.Add(lstControls(i))
Next
This doesn't work properly and following .databind() of my repeater control the controls i specify only appear on the final row. I think this is because i've only declared the controls as NEW once, so i only have one rows worth.
tldr?/ conclusion:
How can i generate new controls of the same type as controls from my list? Something like:
Dim newControl as new Control = type(lstControl(0))
(this obviously doesn't work)
I've found the answer, here are some examples in case anyone else is stuck (i may also change the title so it's more similar to likely search criteria):
dim egTextbox as new textbox
dim egLabel as new label
dim newObject1 as Object = Activator.CreateInstance(egTextbox.GetType)
dim newObject2 as Object = Activator.CreateInstance(egLabel.GetType)
newObject1 is now a textbox
newObject2 is now a label

Gridvew.RenderControl returns empty string

I am trying to export a Gridview to excel. I bind the gridview to a collection and can see that it has 6 data rows but when i call the RenderControl it returns an empty string. Below is the code i am using
Gridview1.DataSource = data;
Gridview1.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
Gridview1.RenderControl(htw);
var outputHtml = sw.ToString();
when i check the outputHtml it is an empty string. What i am doing wrong in this piece of code.
One thing to note is that gridview is lying inside a form with runat='server' tag and i have not overridden the VerifyRenderingInServerForm method.
My best bet is that you have set the visibility of the GridView to false. This will prevent the control from rendering, because well...it's invisible now. The result is an empty string.
If you don't want to show the GridView, just set the Visibility to true before you execute your rendering code and set it back afterwards:
gv_sample.Visible = true;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gv_sample.RenderControl(htw);
var outputHtml = sw.ToString();
gv_sample.Visible = false;
You possibly will run into trouble with the RenderControl method now. If so, make sure you have set EnableEventValidation="false" in the Page directive and override the VerifyRenderingInServerForm method:
public override void VerifyRenderingInServerForm(Control control)
{
return;
}

a ButtonField within DataGrid calling Vb.net as Javascript.... for streaming PDF?

I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub

Programatically created ASP.NET TextBox retains Text value after PostBack even if Control is cleared

I have a drop down menu, and based on which item is selected, I call a web service and then dynamically create some text boxes.
The first time I drop down the menu and select an item, it works perfectly, and the text boxes are created and populated dynamically. However, the next time I drop down the menu (after the first postback), and select something different... after the second postback, the original values remain in the textboxes.
I am clearing all of the text boxes out of the placeholder, then re-creating them, and then setting a NEW value, how can they retain the OLD values... especially if I controls.clear them from the page?
Note: The second time they are being created, the textbox IDs DO end up being the same. Could that have something to do with it? This duplicate ID functionality will need to be supported.
My code, called from Page_Load, is as follows: (edited to add more code)
Private Sub RefreshEntity()
Dim XmlRecords As New XmlDocument
Dim XmlRecordsNode As XmlNode
Dim EntityType As String = EntityTypes.SelectedValue
Dim Entity As String = RecordValue.Value
Dim FieldName As String
Dim FieldValue As String
FieldPlaceHolder.Controls.Clear()
If RecordList.SelectedValue <> "Select..." Then
Try
XmlRecordsNode = LoginInfo.SharePointConnectWebService.GetMetaData(LoginInfo.WSUser, LoginInfo.WSPass, _
EntityType, Entity)
XmlRecords.LoadXml(XmlRecordsNode.OuterXml)
Catch ex As Exception
ConfirmLabel.Text = "<b>Error:</b><br>" & ex.Message.ToString
Return
End Try
Else
SetProperties.Visible = False
Return
End If
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
newLabel.Text = FieldName & ": "
Dim newTextBox As TextBox = New TextBox()
newTextBox.ID = "Field-" & FieldName
newTextBox.Text = FieldValue
Dim newLine As Label = New Label()
newLine.Text = "<br><br>"
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
Next
SetProperties.Visible = True
End Sub
And the RecordValue.Value is a hidden field that gets populated in every Page_Load:
RecordValue.Value = RecordList.SelectedValue
Where RecordList is my DropDown menu.
This is likely due to ViewState or the Posted values clobbering your values.
Once a control is dynamically added to the controls collection it needs to catch up with all the page life cycle events that have already fired. In the case of a post back this means that the ViewState and/or the posted form value will clobber the .text property on the TextBox based on the order you're adding the dynamic controls to the controls collection and setting the .text property.
To fix this you can disable ViewState by setting the .EnableViewState property to false on the dynamically generate controls also add the controls to the controls collection before you set any properties on them.
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
Dim newTextBox As TextBox = New TextBox()
Dim newLine As Label = New Label()
newTextBox.ID = "Field-" & FieldName
newLabel.EnableViewState = False
newTextBox.EnableViewState = False
newLine.EnableViewState = False
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
newLabel.Text = FieldName & ": "
newTextBox.Text = FieldValue
newLine.Text = "<br><br>"
Next
You're not storing the value in a Session variable and then putting it back into the text box later in your code?

Resources