HtmlGenericControl object reference not set to an instance of an object - asp.net

I'm using a pretty simple HtmlGenericControl code that just add CSS dynamically in my code behind
and it gives me object reference not set to an instance of an object which as you see clearly not null
HtmlGenericControl style = new HtmlGenericControl();
style.TagName = "style";
style.Attributes.Add("type", "text/css");
style.InnerHtml = "header{"+ imagePath +";}";
Page.Header.Controls.Add(style);

On which line does it throw the exception? Which object is the offending one? Add a breakpoint to your code and let us know. Could it be that imagePath is not set up correctly?
Update:
I just created a brand new C# WebForms project and added the following to the Page_Load method of Default.aspx.cs and then inspected the source and it does exactly what you'd expect:
var imagePath = "contentHere";
HtmlGenericControl style = new HtmlGenericControl();
style.TagName = "style";
style.Attributes.Add("type", "text/css");
style.InnerHtml = "header{" + imagePath + ";}";
Page.Header.Controls.Add(style);
This is added to the end of the head tag of my HTML page:
<style type="text/css">header{contentHere;}</style>
To confirm, I have the following using statements on the page:
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;

Related

Add Link Button in specific location

My current scenario is I retrieved the HTML of a page using the following method.
readStream = New StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet))
Dim fullString As String = readStream.ReadToEnd()
I did further formatting of the HTML before setting it to the innerHtml of my div.
displaystring = Regex.Replace(fullString, "<div.*?>", "<div>")
displaystring = Regex.Replace(fullString, "<span.*?>", "<span>")
displaystring = Regex.Replace(fullString, "<table.*?>", "<table>")
For example, I have a part of HTML code which is
<a>Brazil</a>
And I have tried fullstring = Regex.Replace(fullstring, "<a>Brzail</a>", <asp:Linkbutton name="lnkTest" runat="server"). And I realized it cannot work because ASP controls cannot be appended as string.
How can I control.Add just after <a>Brazil</a>? Any other suggestions are welcome too.
You cannot add ASP.Net Server control like this. You can use html control anchor tag or button and on click of this you can make an AJAX call.
Sample code will be like this
fullstring = Regex.Replace(fullstring, "<a>Brzail</a>", "<a href='#' onclick='clickMe'>Link</a>")
In Server side C# you can write a page method
like `
[PageMethod]
public static string MyMethod()
{
//Your logic
return "";
}
`
In javascript
function cickMe()
{
$.ajax({
url: "Sample.aspx/MyMethod",
success: function(data){
//your logic
}
});
}

Change the content of a Css Class through Code Behind in asp.net

I need to change the CONTENTS of a css class through asp.net code behind. The reason why I need to do this is because i have an external user control that uses a property called "stylefolder" instead of the normal cssclass.
I'm really out of ideas, I tried to open the css file and replace text, but then after i also need to save it. So the css file is permantly modified which I don't want.
Please help
The way you are trying to tackle your problem does not seem logical. Temporarily modifying css depending on the stylefolder property seems crazy. Could you not use inline styling depending on the property value and store some data in the session ?
Make a separate file for that user control and at run time load the file on the condition basis like this
protected void Page_Init(object sender, EventArgs e)
{
if (usercontrol)
{
// load the css relateed to user control
HtmlLink cssPdf = new HtmlLink();
cssPdf.Href = "path to user control file";
cssPdf.Attributes["rel"] = "stylesheet";
cssPdf.Attributes["type"] = "text/css";
cssPdf.Attributes["media"] = "all";
Page.Header.Controls.Add(cssPdf);
}
else
{
//load regular file
HtmlLink cssPdf = new HtmlLink();
cssPdf.Href = "path to regular file";
cssPdf.Attributes["rel"] = "stylesheet";
cssPdf.Attributes["type"] = "text/css";
cssPdf.Attributes["media"] = "all";
Page.Header.Controls.Add(cssPdf);
}
}

RegisterStartupScript not working inside an Update Panel to open file in new tab in asp.net

I am trying to open a file in new tab on click event of a link button inside gridview using ScriptManager.RegisterStartupScript inside update panel, but its not working. The Code is as below :
filename = Server.UrlEncode(filename);
string js = "<script>window.open('ViewReports.aspx?filename=" + Server.UrlEncode(filename) + "', '_newtab');</script>";
ScriptManager.RegisterStartupScript(UpdatePanel1,UpdatePanel1.GetType(),"Pop up",js,true);
This also not working:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), js, true);
And when I am using below code outside Update Panel it works:
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "dateSrpt", "<script>window.open('ViewReports.aspx?filename=" + Server.UrlEncode(filename) + "', '_newtab');</script>");
There is problem with your inline javascript. It doesn't work with the inline javascript. when I segregated it to the aspx page as separate javascript function and called the function inside the Registerstartupscript, It worked.
Javascript
function OpenPopup() {
window.open('PulseUserManagement.aspx', null, 'height=500, width=1100, status=no, resizable=no, scrollbars=yes, toolbar=no,location=no, menubar=no');
}
CS code
ScriptManager.RegisterStartupScript(updatepanel1, updatepanel1.GetType(), "Pop up", "OpenPopup();", true);
Please try like this, it works.

How do you add HTML headings dynamically in ASP.NET?

What is the server side control used to add an H4 to the markup from the code behind?
var h4 = new HtmlGenericControl("h4");
h4.InnerHtml = "Heading Text";
parentControl.Controls.Add(h4);
I recommend creating an HtmlGenericControl in your code-behind. The benefit of these over Literals is that they are proper HtmlControls, with the ability for you to programmatically set and modify properties such as InnerHtml, CssClass, Style etc.
HtmlGenericControl myH4 = new HtmlGenericControl("h4")
{
ID = "myH4",
InnerHtml = "Your Heading Here"
});
yourContainerControl.Controls.Add(myH4);
You could use an asp:Literal control - this just writes out the exact text that you set it to.
E.g:
Dim myLiteral as Literal = new Literal()
myLiteral.Text = "<h4>My Heading</h4>"
Then add your Literal to the page.
There is nothing like a <asp:H4 /> control. However, you can add any HTML element to a page via HtmlGenericControl type in your code behind.
For example, to create it:
HtmlGenericControl headerControl = new HtmlGenericControl(HtmlTextWriterTag.H4.ToString());
headerControl.ID = "myHeader";
headerControl.InnerHtml = "Hello World";
placeHolder.Controls.Add(headerControl);
To access it from code behind later:
HtmlGenericControl headerControl = FindControl("myHeader") as HtmlGenericControl;

How to add a server image control to html container using innerHTML =

I have a td that I want to inject with a server image control (asp.net) using innerHTML = "". The webcontrol's toString is giving the type.
Is there a way to extract the generated from the server control?
Or, is there a different solution...?
Thanks
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
img.RenderControl(new HtmlTextWriter(writer));
td.InnerHtml = sb.ToString();
or the more obvious
td.Controls.Add(img);
You can use the RenderControl method to get the output HTML.
Ex:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
class Program
{
static void Main()
{
var img = new Image();
var hw = new HtmlTextWriter(Console.Out);
img.RenderControl(hw);
hw.Dispose();
}
}
Output:
<img src="" style="border-width:0px;" />
The first part of your question looks like you're asking how to inject an image at runtime into a table cell.
If the table cell is part of your ASP.NET page, you could do something like:
<td id="imageCell" runat="server"/>
In your code behind:
Image img = new Image();
img.ImageUrl = "mypic.jpg";
imageCell.Controls.Add(img);

Resources