Controls in a telerik control not accessible from .cs file - c#

I am using telerik controls in my c# asp.net project. I am trying to disable a div in a telerik navigation menu from the .cs file. For example:
if (Emp_Role == "1" || Emp_Role == "5")
{
DivLeave.Visible = true;
}
I try run the project I get this error:
CS0103: The name 'DivLeave' does not exist in the current context
Here is an example of the aspx code
<telerik:RadMenu runat="server" ID="RadMenu1" Skin="Sitefinity" OnClientItemOpened="itemOpened"
Width="670px" Height="26px" EnableShadows="true">
<Items>
<telerik:RadMenuItem Text="Expenses" PostBack="false">
<Items>
<telerik:RadMenuItem CssClass="Stores" Width="640px">
<ItemTemplate>
<div id="DivLeave" class="Wrapper">
<h3>
Expense Management</h3>
</div>
Can anyone help with this? If I place the div outside the telerik control it works fine. This is so frustrating!
Kind regards,
R

First, you have to use a asp.net control ( or at least a control that runs in server ) to be able to access it from code behind. For example.
<asp:Label ID="DivLeave" runat="server"></asp:Label>
Second, to get a control inside a Telerik control you need som special code. In your example, you can do something like this:
// Find menuitem by css class
RadMenuItem expenses = RadMenu1.FindItem(i => i.CssClass == "Stores");
// Find control inside menuitem
Label label = expenses.FindControl("DivLeave") as Label;
label.Visible = true;
To learn more:
Accessing Controls Inside Templates

Doing it client side will also work and you won't have to make the div become server side.
Using jQuery you can have:
if (Emp_Role == "1" || Emp_Role == "5")
{
Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "show_divleave", "$(function() { $(\"div[id$='DivLeave']\").each(function(index) { $(this).css(\"display\", \"\"); }); });", true);
}
This assumes those div elements are initially hidden using "display: none;" CSS rule.

Related

.NET webform Hide a HTML td column in backend server (Update Panel, Content Template)

I have an instance, it shows a listView.
the listview is in the update panel, it needs to response to each data source binding and show/hide a column in the listView table by checking a Session.
I cannot simply add
<% if((int)Session["v1"] ==1) { %> <td>Hi</td> <%}%>
as the exception throw saying that the update panel cannot update when <% %> exists.
(but it works for the control outside of the update panel)
I think I can do it by javascript but I just want to make sure if there is a smarter way to do in the backend.
class='<%# HiddenClass %>'
and changing this parameter during onload (change HiddenClass to empty string if the column should show.
It works for the item's column (in the ItemTemplate) but it doesn't work for the item's header column LayoutTemplate (i think it is because data source binding only re-rendered the fields in the ItemTemplate and not included LayoutTemplate.
currently, I was able to hide it to set the runat="server" Visible to false if for each data source binding of the listview. But it looks very complicated when I need to hide more columns (need to create more ID and asp.net cannot set visible of fields by class).
Wrap the <td></td> with a PlaceHolder and set it's Visibility property from code behind.
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
<td>Hi</td>
</asp:PlaceHolder>
And then in code behind
if ((int)Session["v1"] == 1)
{
PlaceHolder1.Visible = true;
}

Access HTML Inputs on Postback in ASP.NET

I've struggled with this for days now, trying to access html inputs, i.e. checkboxes or textboxex generated at runtime based on DB results. My HTML which is added as a literal control to a asp placeholder looks like this:
<div class='cart-item'>
<div class='product-name'> <h3>gold baseball figure</h3></div>
<img src='Graphics/gold-trophy.png'></img>
<div class='inventory-short-description'> <p>A finely crafted gold plated baseball figuring to top your choice of trophey base (sold seperatly).</p></div>
<div class='clear'></div>
<div class='item-price'><p>$22.95</p></div>
<div class='cart-item-checkbox'><label><input type='checkbox' id='1' name='1' runat='server'/> Select </label>
<a href='products.aspx?viewItem=1'>view item </a></div></div
Question is, how do I access this check box in the .cs code behind page?
My code which is generating this html and adding it to the page is in the overrided OnInit method. Looking at the placeholder on postback shows that the checkbox is in the literal control.
I've tried:
Page.FindControl() returns null when searching for dynamic control
ASP.NET page_init event?
FindControl() return null
http://forums.asp.net/t/1336244.aspx?finding+HTML+control
....And countless others.
Yesterday I used a hackish way to set the value of these checkboxes to a asp.net hidden field using jquery. My coworkers (all java devs) say this seems to be the wrong way to access these elements. Is there a better way? I'm beginning to think I've coded myself into a spot I can't get out of.
Thanks for the help.
In your .aspx
<asp:Repeater ID="rptItems" runat="server" EnableViewState="False">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" />
</ItemTemplate>
</asp:Repeater>
In your .aspx.cs file you can access repeater in postback events as below
foreach (RepeaterItem rptItem in rptItems.Items)
{
TextBox txtName = (TextBox)rptItem.FindControl("txtName");
if (txtName != null) { System.Diagnostics.Debug.Write(txtName.Text); }
}

Using (static)HTML Controls in Code-Behind, Coding with C#/ASP.NET

I am working in VS10 using C# in ASP.NET. In my design form, I have a textArea(standard HTML control).
<textarea id="Text1" rows = "8"; cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
Now in my code-behind page, I am using C# to code the controls. I have given the textArea an auto-expand functionality which I require thru out my project. I need this TextArea as a server control, like when we put a textBox in the design page, we can use it in the code-behind page to code, since it is a server control. However, textArea isn't a server control.
I have gone thru the previous posts on the site but i did not get anything enough useful.
I have even tried using [<% %>] system, and [runat="server"] but it did not help.
What i wanna do is to use the textArea in the Code-behind page, i.e. call it in the coding space, just like we can call the TextBox control objects.
So, can anyone please help me with this,,,
Regards..
javascript for autogrowing text box is:
<script type="text/javascript">
function AutoGrowTextArea(textField)
{
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = textField.scrollHeight + "px";
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = (textField.scrollHeight * 2 - textField.clientHeight) + "px";
}
}
}
</script>
Try this
add runat="server" to the tag
<textarea id="Text1" runat="server" rows = "8" cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
you can manipulate raw html controls setting the runat="server" propery of the control.
<textarea id="Text1" runat="server" rows = "8"; cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
You can add runat="server" in your markup and it will be a server control.
You can also create server controls in your code behind. Declaration (In Visual Basic):
Protected WithEvents foo As Global.System.Web.UI.HtmlControls.HtmlGenericControl = Global.System.Web.UI.HtmlControls.HtmlGenericControl("textarea")
If you want to use something in all your project, you can declare a class inherited from Control or HtmlGenericControl and you can implement whatever you need to implement everywhere where you your new control.
<asp:TextBox id="thisIsMyTextBox" runat="server" multiline="true" width="200px" onkeyup="AutoGrowTextArea(this)" height="80px" style="resize:none;"></asp:TextBox>
You can play with the width/height as you wish !
function AutoGrowTextArea(textField)
{
if(textField.Lenght()%50==0)//50 is the number of character in your textbox
{
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = textField.scrollHeight + "px";
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = (textField.scrollHeight * 2 - textField.clientHeight) + "px";
}
}
}

c# - error using FindControl on div id

I have an ASP.NET site that I am trying to access div elements by their ID from the C# code behind file. Essentially I want to see if a div element exists, and if so, alter its properties.
I've found many resources out there that point to a dozen different solutions and none of them seem to work.
HTML on ASP.Net Page:
<div class="contentArea">
<div class="block" id="button1" runat="server">
Some Content Here
</div>
<div class="block" id="button2" runat="server">
Some Content Here
</div>
<div class="block" id="button3" runat="server">
Some Content Here
</div>
</div>
C# Code Behind (examples I've tried):
System.Web.UI.HtmlControls.HtmlGenericControl div1 = (System.Web.UI.HtmlControls.HtmlGenericControl)this.FindControl("button1");
div1.Attributes["class"] = "classNameHere";
or
Control div1 = this.FindControl("button1");
div1.GetType();
When the code gets to the second line of each of the above examples, I get an error:
Object reference not set to an instance of an object.
If I try the following:
if (div1 != null)
{
// Do Something;
}
Nothing ever happens because div1 is always set to null. Ironically, if I look at the Locals window and examine this, I can see the button# ids in the listing, so I know they are there, but the system is acting like it isn't finding the control.
My ultimate goal is to find the max id # of the button divs (looking at my html example, the max id would be 3 (button3). Maybe there is a better way to go about it, but either way, once I have my max id, I want to be able to touch each div and alter some css properties.
Although I could easily do all of this via jQuery, in this instance I need to do this in C#.
Any help is much appreciated. If you need more info, let me know.
UPDATE
I created a new C# web project from scratch. After adding a masterpage (and not altering it) and adding a webform using masterpage, I only added one line to the webform under Content ID="Content2":
<div id="button1"></div>
From c# code behind I still run into the same exact issue as before.
FINAL UPDATE AND ANSWER
I'm shocked no one (including myself) caught my mistake from the above update. I never put runat="server" when I created a new project from scratch under the div. Here is how I fixed my problem under my new project from scratch:
Add runat="server" to div:
<div id="button1" runat="server"></div>
Then I did a FindControl on the ContentPlaceHolder under the MasterPage:
ContentPlaceHolder myPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
Note: This is what the ContentPlaceHolder code looks like on the Site.Master page created by default:
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
After finding this ContentPlaceHolder in code behind, I then searched within this placeholder for button1:
using System.Web.UI.HtmlControls;
HtmlControl myControl = (HtmlControl)myPlaceHolder.FindControl("button1");
Finally I check to see if myControl is null:
if (myControl != null)
{
\\ Do Something
}
When I ran this code, it found the div I was looking for. Here is the complete code behind all put together:
using System.Web.UI.HtmlControls;
ContentPlaceHolder myPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
HtmlControl myControl = (HtmlControl)myPlaceHolder.FindControl("button1");
if (myControl != null)
{
// Do Something
}
If your page is using a MasterPage, the div control will not be in the main collection of controls. That collection only contains the Content controls pointing to the ContentPlaceholder of your MasterPage.
There are three options:
Use FindControl on the Content control: contentControl.FindControl("button1");
Do a recursive FindControl until you find the control you need
Normally, a declaration of your div control is added to your designer.cs codebehind, so you can directly access the control by its name: button1.Attributes["class"] = "classNameHere";
Update
I have created a MasterPage, added a Content Page to it, and added <div id="button1" runat="server">Some text</div> to the Content Page.
In the codebehind of my Content Page, I added this code:
protected void Page_Load(object sender, EventArgs e)
{
var control = FindHtmlControlByIdInControl(this, "button1");
if (control != null)
{
control.Attributes["class"] = "someCssClass";
}
}
private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) && childControl is HtmlControl)
{
return (HtmlControl)childControl;
}
if (childControl.HasControls())
{
HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
if (result != null) return result;
}
}
return null;
}
This works for me.
If you add runat=server please add it at last of the div:
This will work
<div id="divBtn" class="mybuttonCass" runat="server">
However, this will not
<div runat="server" id="divBtn" class="mybuttonCass">
By doing that, you can modify any property from codebehind as:
divBtn.Style["display"] = "none";
This works even with masterpages. The div is not included in a masterpage.
You need to add a runat=server attribute to any control that you want to access in code behind. See this article for more help.
Accessing <div> from both javascript and code-behind
I cannot seem to be able to reproduce your problem, any chance your DIV's are within a template control such as UpdatePanel, Repeater, or Grid?

Highlighting Menu Bar in ASP.NET Web Application

I built a web application using ASP.NET Visual Studio 2010 with Master Pages. As you will see that the project gives us a default menu bar item. I have 5 pages (links) listed on those menu bars. Now when a user goes to a specific page I want to highlight that menu bar link. I dont know how to do that :(
I tried this on the Master Page Code Behind but it didnt work too:
foreach (MenuItem item in NavigationMenu.Items)
{
var navigateUrlParams = item.NavigateUrl.Split('/');
if (Request.Url.AbsoluteUri.IndexOf(navigateUrlParams[navigateUrlParams.Length - 1]) != -1)
{
item.Selected = true;
}
}
And in my mark up view I have this:
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" OnMenuItemClick="NavigationMenu_MenuItemClick">
<Items>
<asp:MenuItem Text="Test1"/>
<asp:MenuItem Text="Test2"/>
<asp:MenuItem Text="Test3"/>
</Items>
</asp:Menu>
</div>
So basically whenever user comes to Test1.aspx page, I want the menu item of Test1 to be highlighted. How should I do that?
Any help will be appreciated! Thank you...
Use CSS link classes to implement this:
http://www.w3schools.com/css/sel_active.asp
And unless you "need" to do something programmatic against these link items, use HTML anchor links instead. Create them as list items:
<ul class="menu">
<li>
Link 1
</li>
</ul>
What I'm saying is to question if controls are necessary here (not familiar with your project), and to keep the markup simple whenever possible.
First make sure that your menu items all have an Id property
In your master page code behind in the page Load handler do something like this
if (!Page.IsPostBack)
{
if(Page is Default)
liHome.Attributes["class"] += " active";
}
In this example you would check the "type" of the currently viewed page and append the to the class attribute for the currently navigated link. you could define a css property for active something like
.active
{
background-color: Red;
}

Categories