I have to create a series of controls(Hyperlink and Label) in .aspx file.The most important thing is that I have to control the ID of the generated control.
I write some code in my .aspx file like this:
<%for (int i =1; i <= 5; i++){%>
<asp:HyperLink ID="<%#GetContorlName("HyperLink",i,1)%>" CssClass="c083e01" runat="server">HyperLink</asp:HyperLink>
<%} %>
GetContorlName() is a function defined in codebehind file which return a string represent ID.
However,This doesn't work,It cannot compile.
Who can help me to fulfill this task?Please Remember I have to dynamically create controls in .aspx file,not in .cs file.
Any help will be appreciated!
Use ClientID.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Use databinding, and nest the controls in a repeater. Remember that Enumerable.Range() can be a valid datasource.
try this method for your Hyperlink
TextBox txt = new TextBox();
txt.ID = "strtxtbox";
txt.CssClass = "CSS1";
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
txt.RenderControl(htmlWriter);
//lbl is an aspx label
lbl.text += #"<td style='width: 5%;'>" + sb.ToString() + "</td>";
Related
I have an Aspx page that displays a GridView. The gridview would appear with data that was depending on which catergory was selected from a drop down menu. The user has the option to then download this as a CSV file (export to CSV). I now want the Gridview not to appear (beacuse it is so large it often just hangs) but instead to be able to download a CSV file with the data from the gridview. I have successfully built the button allowing for the download of this data by clicking the button. However, I now cannot open the page without the gridView appearing. I tried to comment out the Gridview code - this just broke the page. I tried to set the gridview as Visible="False" but this did not work either. What else can I do to prevent the gridview from appearing and the user to be taken straight to a download dialogue box?
wrap your Gridview to a div and set it to display:none in asp.net code –
Ex: <div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div> like this
You can load your data in DataSet or DataTable from Code Behind and then export it directly to Excel/CSV without assigning it to GridView such as in the following example to export it to Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
If you get errors like control must be placed in inside of form tag you may also be required put the following code in your backend (Reference: export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C# Version of above code:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}
When trying to render the HTML of an ascx UserControl from a WebService, I get the error RegisterForEventValidation can only be called during Render.
This is a duplicate of this question. However the answers given do not work...
The solution always involves EnableEventValidation="false" and override VerifyRenderingInServerForm but these are only available on a Page, not on a Control (what the ascx is).
When changing the ascx to an aspx, the following code fails: page.LoadControl("mycontrol.ascx/aspx") and rendering an aspx is apparently not so easy according to this question.
The Question
How can I render my ascx without the exception?
Bonus question:
Why is EnableEventValidation not available on a Control while there are many examples on the net that claim otherwise? (StackOverflow, CodeProject, ...)
I found the solution:
var page = new System.Web.UI.Page();
// Or RenderControl throws 'RegisterForEventValidation can only be called during Render'
page.EnableEventValidation = false;
// Or generates a second hidden field with ID=_VIEWSTATE
page.EnableViewState = false;
var sb = new StringBuilder();
var ctl = (SomeAscx)page.LoadControl("SomeAscx.ascx");
using (var sw = new StringWriter(sb))
using (var htw = new HtmlTextWriter(sw))
{
ctl.RenderControl(htw);
}
string result = sb.ToString();
Key was setting:
page.EnableEventValidation = false;
page.EnableViewState = false;
i am working with String Builder and a Tree view control which i am generating Dynamically in my page.
This is what i have tried with :
Public sbMenu As New StringBuilder
In Page Load Event
Dim TreeView1 As New TreeView()
TreeView1.ID = "tree1"
TreeView1.ShowCheckBoxes = TreeNodeTypes.All
TreeView1.ShowLines = True
TreeView1.Nodes.Clear()
I am loading the TreeView1 using Database data and atlast appending to my string builser object as
sbMenu.Append("<div>")
sbMenu.Append(TreeView1)
sbMenu.Append("</div>")
But the sbMenu doesn't contain the TreeView1 instead it is storing
System.Web.UI.WebControls.TreeView
Can you please help me , By how my stringBuilder can hold the TreeView control and can make use of it..
I will use this in my .aspx page as
<%= sbMenu.Tostring() %>
here i need the TreeView control..
You can get a control's HTML by calling RenderControl. E.g.
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
using (var writer = new HtmlTextWriter(sw))
{
myControl.RenderControl(writer);
}
string html = sb.ToString();
Or in VB:
Dim sb = New StringBuilder()
Using sw As New StringWriter(sb)
Using writer As New HtmlTextWriter(sw)
myControl.RenderControl(writer)
End Using
End Using
Dim html As String = sb.ToString()
Can ASCX or ASP.net files be saved as HTML files? if so, how?
yes, it is possible, to get the rendered content of a User Control, do the following :
StringWriter output = new StringWriter();
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl("path to ascx file");
pageHolder.Controls.Add(viewControl);
HttpContext.Current.Server.Execute(pageHolder, output, true);
string htmlOutput = output.ToString();
Am sure you can adapt the above for ASPX page if required :-)
From there, saving that to a file should be fairly straight forward.
HTH.
D
You can do this directly with the Render method of a Page or UserControl. Since the method is protected, you will need to create a control that subclasses either. From there, you've got access to do whatever you need.
e.g.
public partial class MyPage: Page
{
public string GetPageContents()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (HtmlTextWriter writer = new HtmlTextWriter(sw))
{
Render(writer);
}
return sb.ToString();
}
}
You probably wouldn't want to call this anytime before the PreRenderComplete event of the page though, since otherwise you can't be sure all child controls/events/etc have finished.
Pardon me, this really is a noob question but please understand that I do not have much ASP.NET experience. All I need to do is:
1) Open up the following SQL query:
SELECT myid FROM mytable
2) For each record, generate this fragment of HTML:
<img src="http://someurl/__myid comes here as well__/small.png" />
Its easy for me to use the classical ASP <% do until recordset.eof ... loop %> style loops but I need it in ASP.NET style, probably perform the operation in Page_Load event and use intrinsic ASP.NET controls.
Use a repeater control. In the ItemTemplate, you can put whatever you would like to be generated for each record returned from your query.
http://articles.sitepoint.com/article/asp-net-repeater-control
add this in the aspx page source
<td id="urLink" runat="server">
</td>
add this in the Page_Load event
SqlConnection con = new SqlConnection();
con.connectionstring = "your connection database";
SqlDataReader reader;
SqlCommand command = new SqlCommand(con);
command.Commandtext = "SELECT myid FROM mytable";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
while(reader.Read())
{
urLink.innerHTML += "<a href="#mynameanchor" onClick="myfunction( " + reader["myid"].tostring() + " );">
<img src="http://someurl/" + reader["myid"].tostring() + "/small.png" /></a>";
}
Looks like the onclick is a javascript event which means you can write out the HTML markup to a string and then append it all into a literal control. Remember to use a stringbuilder :)
here's a very basic example:
// get data from database and into a reader before
StringBuilder links = New StringBuilder();
while(reader.read())
{
links.appendFormat("<a HREF='id_{0}'>{0}</a>", reader["ID"]);
}
ltlLinks.Text = links.ToString();