ASP literal not working - asp.net

I am trying to get an asp: literal to work but apparently I am doing something wrong because I am getting an
Object Referece not set to an instance
of the Object
error
This is my code:
in the ascx page:
<span class="span1">
<asp:Literal ID="litFile" runat="server"></asp:Literal>
<strong><asp:Literal ID="litFile2" runat="server"></asp:Literal></strong>
</span>
and
in the ascx.cs page:
protected void _ItemBound(object sender, RepeaterItemEventArgs e)
{
((Literal)e.Item.FindControl("litFile")).Text = "a";
}
Any idea please?
C

We need more code to know for sure, but what this looks like to me is that the literal is actually outside the repeater that's firing the _ItemBound method. Otherwise, e.Item.FindControl should be able to find it. Make sure litFile is inside the ItemTemplate in your repeater control, rather than elsewhere in the page.

You shouldn't need to cast it, nor should you need to search for it.
Try just:
litFile.Text = "a";
If this doesn't work, we will need to see more code to work out what's going on.

Since your using FindControl I assume your in a repeater or something, so try this
Literal litFile = repeaterName.FindControl("litFile");
litFile.text = "a";
I code in VB so sorry if my syntax is off.

Related

code behind and postback in master page doesnt work

i have a very annoying problem...
i had a textbox and a link in my master page. i wanted to use the link button to pass the text of textbox as a query string for some filtring stuff.
but i understood that the cod behind of link bottun doesnt work at all and it just refresh the page.
i tried to do it by jquery by window.location.href but it only worked at the first page and other pages couldnt get the postback.
i changed everything and tried to use radsearchbox.
this control works fine but it only works in every page except the main page.
let me be more clear:
it works great onhttp://kalashabakeh.ir/product.aspx?groupID=1&subgroupID=0
but it doesnt work at www.kalashabakeh.ir
i really dont know what can couse so many problems. maybe my script manager or a js file or something?
plz help me!
here is my current code with radsearchbox:
in masterpage.master:
<telerik:RadSearchBox runat="server" ID="RadSearchBox2"
CssClass="searchBox" Skin="Silk"
Width="200" DropDownSettings-Height="300"
DataSourceID="SqlDataSource_search"
DataTextField="product_name"
DataValueField="product_key"
EmptyMessage="جستجو..."
Filter="Contains"
MaxResultCount="20"
OnSearch="RadSearchBox2_Search">
</telerik:RadSearchBox>
in master page codebehind:
protected void RadSearchBox2_Search(object sender, SearchBoxEventArgs e)
{
Response.Redirect("product.aspx?searchID="+ e.Text.ToString(),false);
}
Is it a typo or something like that. Your Rad searchbox control ID is RadSearchBox2 and it's calling a event handler named RadSearchBox2_Search whereas you are having a handler method named RadSearchBox1_Search. See below pointed
<telerik:RadSearchBox runat="server" ID="RadSearchBox2"
.....
OnSearch="RadSearchBox2_Search"> <--Here
</telerik:RadSearchBox
protected void RadSearchBox1_Search(object sender
^-------- Here
i finally found the answer...
as people discussed here
its a kind of a bug in iis7...
this code solved my problem thank to Eric
just add this code in master page.
public void Page_PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Page.Form.Action) && Request.Url.AbsolutePath.ToLower().EndsWith("/default.aspx"))
this.Page.Form.Action = "Default.aspx";
}
Now i can light up my cigurate ...

Defining where usercontrol output will be

I am new to ASP.NET and user controls. I am trying to generate a javascript array from my C# code.
On the main .aspx page I have this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="main.aspx.cs" Inherits="main" %>
<%# Register Src="~/table.ascx" TagPrefix="uc1" TagName="myTable" %>
Then on my table.asc.cs I have this:
protected void Page_Load(object sender, EventArgs e)
{
(...)
this.LoadDataFromDB();
(...)
}
private void LoadDataFromDB()
{
(...)
Response.Write(array);
(...)
}
My problem is that the array is being written before the <html> tags. It still works fine, but, how could I put it inside the <head> tags for instance?
Thank you
UPDATE:
I added this to my main.aspx
<asp:Literal ID="Literalarray" runat="server" Mode="PassThrough" Text="" />
and this to my ascx.cs:
Literal Literalarray= new Literal();
Literalarray.Text = output;
What am I missing?
Use a Literal control instead of Response.Write. Place it on your control somewhere and set its Text property.
You have to place it on your control, not on your page and you don't need to reinitalize it.
This code in the ascx.cs:
Literal Literalarray= new Literal();
Literalarray.Text = output;
should be:
Literalarray.Text = output;
Which should be in the Page_Load as a designer file will declare the literal type and allocate the space for it. By declaring a new one, the old one may be hidden. Also, be aware that if you are generating a JavaScript array that you also generate the script tags as part of the output as a literal doesn't do much decorating around the result.
I'd probably suggest putting a literal in the head on the main.aspx and load the data in there that way for one idea.
You could also do dynamic controls so that in the table.ascx.cs you create a Literal like you did previously and then add that to the head of the page assuming the head tag has a "runat=server" attribute so the code behind can use it. I'm pretty sure that in the code behind for the table you could do something like this:
Literal Literalarray= new Literal();
Literalarray.Text = output;
this.Page.head.AddControl(Literalarray);

Databinder.Eval double quotes

I have a problem and I can't figure it out how to solve it. I search for solutions but they did not work. So, I have a Datalist with ItemTemplate. I need to add google analytics on onclick event to <a> tags. I tried to add the onclick event like
onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click on',<%#DataBinder.Eval(Container.DataItem,"URL")%>']);" <br />
but I get a yellow error screen with the message "..tag is not formatted correctly".
I also tryed replacing double qoutes with &qout; but no success. I also tried
onclick='<%# string.Format("_gaq.push(['_trackEvent','Homepage','Click on last awarded company','{0}']);", DataBinder.Eval(Container.DataItem, "URL") %>' <br />
but this also not worked.
Have you got any idea how could I solve this problem?
You really should do this kind of complex databinding in the "OnItemDataBound" event in the code behind. Have a look at the relevant MSDN page.
<asp:DataList id="ItemsList" OnItemDataBound="Item_Bound" runat="server">
Code Behind:
public void Item_Bound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// find your link
HyperLink link = (HyperLink)e.Item.FindControl("MyFirstHyperLink");
// so something nice with your link here, for example add attributes.
string a = DataBinder.Eval(e.Item, "URL", "_gaq.push(['_trackEvent','Homepage','Click on last awarded company','{0}']);");
link.Attributes.Add("onclick", a);
}
}
disclaimer: I haven't actually tested this code so you might need to make adjustments here and there. It merely serves to give you an idea of the direction to go.
Could you please try below?
Test
I've met the following scenario: I had to reuse some function that returns a collection of dynamic objects, from other assembly. Generally, there is a possibility to publish the dynamic object to other assembly, by using [assembly: InternalsVisibleTo("Some.Assembly")], because the dynamic objects are internal to their assembly. Not having the choice, I've tried the item data binding method solution to add the script, but dynamic objects are not accessible there, even if I used Eval. But Eval works in the markup, and there the quote/apostrophe problem occurs. My solution was HTML escaping:
onclick='<%# "doSomething(&apos;" + Eval("DataProperty") + "&apos;, this);"%>'

Access dynamically generated control from code behind

I load a piece of html which contains something like:
<em> < input type="text" value="Untitled" name="ViewTitle" id="ViewTitle" runat="server"> </em>
into my control. The html is user defined, do please do not ask me to add them statically on the aspx page.
On my page, I have a placeholder and I can use
LiteralControl target = new LiteralControl ();
// html string contains user-defined controls
target.text = htmlstring
to render it property. My problem is, since its a html piece, even if i know the input box's id, i cannot access it using FindControl("ViewTitle") (it will just return null) because its rendered as a text into a Literal control and all the input controls were not added to the container's control collections. I definitely can use Request.Form["ViewTitle"] to access its value, but how can I set its value?
Jupaol's method is the prefer way of adding dynamic control to a page.
If you want to insert string, you can use ParseControl.
However, it doesn't cause compilation for some controls such as PlaceHolder.
Your process is wrong, you are rendering a control to the client with the attribute: runat="server"
This attribute only works if the control was processed by the server, you are just rendering as is
Since your goal is to add a TextBox (correct me if I'm wrong), then why don't you just add a new TextBox to the form's controls collection???
Something like this:
protected void Page_Init(object sender, EventArgs e)
{
var textbox = new TextBox { ID="myTextBoxID", Text="Some initial value" };
this.myPlaceHolder.Controls.Add(textbox);
}
And to retrieve it:
var myDynamicTextBox = this.FindControl("myTextBoxID") as TextBox;
I have created several working examples and they are online on my GitHub site, feel free to browse the code

How to find the HtmlInputCheckBox of a repeater control in code behind file without using runat ="server" tag

Inside repeater i have a html checkbox , now i want to access this checkbox in code behind file to check whether the checkbox is checked or not. but i dont want to user runat="server" tag , how can i do this my code as above
<input id="cbfdgroup" class="checkitem" type="checkbox" name="fd_cb_group[]" value='<%#Eval("FoodItemsUid") %>'>
in code behind file i am trying to access like this
foreach (RepeaterItem ri in rptMenu.Items)
{
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox)ri.FindControl("cbfdgroup");
if (chk.Checked)
{
}
}
}
but this is giving error as object referrence is not set to instance of an object.. how should i get this control in code behind file without using runat = "server" tag
It is not possible. To clarify, the runat="server" portion is doing just what it says. It is saying that this control should be made available and accessible to the server.
Code which is in the code-behind is code which is running on/executed by the server. So logistically, if the control is not made available to the server, the it cannot be manipulated by code (hence when it will not show up in intellisense either.)
I don't believe what you are asking is possible. runat=server is what makes controls available to the code behind. If you remove that attribute, your code behind is simply not aware of the control in any way.
A little bit more explanation:
The codebehind executes on the server. Therefore, any control you want to access in your codebehind must have runat=server in order to be available. The two are inseparable.
you don't need to read the items from repeater
assuming that you are sending a postback to the server (http post)
you can read the selected checkbox by simply:
string x = Request["fd_cb_group[]"];
it is more than 1 it will separate by comma, just use split the get a list of string of selected values.
the whole thing would be something like that:
protected void Button1_Click(object sender, EventArgs e)
{
string x = Request["fd_cb_group[]"];
string[] allSelectedOnes = x.Split(',');
foreach(string item in allSelectedOnes)
{
//your custom code for the selected checkboxes
}
}

Resources