How to disable user control from code-behind? - c#

I have 2 user controls in an ASPX page. By default the second user control should be disabled. In that user control i am having only one text box. So i find the control in the page load event like this:
TextBox txtLocation = (TextBox)PI_CompLocationTree.FindControl("txtLocation");
txtLocation.Enabled = false;
But i am getting txtLocation as null. How do I get the control in the ASPX page from the ASCX control?
My Updated Code..In Aspx page..
<%# Register Src="~/UserControl/PI_CompLocationTree.ascx" TagName="PI_CompLocationTree"
TagPrefix="uc1" %>
<div id="Div2">
<div class="location">
<div class="usLocation">
<uc1:PI_CompLocationTree ID="PI_CompLocationTree1" runat="server"/>
</div>
</div>
</div>
In Page Load...
PI_CompLocationTree PI_CompLocationTree = new PI_CompLocationTree();
protected void Page_Init(object sender, EventArgs e)
{
var userControl = (PI_CompLocationTree)this.FindControl("PI_CompLocationTree1");
userControl.EnabledTextBox = false;
}
In ASCX Page...
<asp:TextBox ID="txtLocation" CssClass="fadded_text fadded_text_ctrl" Style="width: 260px;
float: left;" runat="server" Text=""></asp:TextBox>
In ASCX Code Behind...
public partial class PI_CompLocationTree : System.Web.UI.UserControl
{
public bool EnabledTextBox
{
get { return txtLoc.Enabled; }
set { txtLoc.Enabled = value; }
}
}

Use FindControl Methods as Follow..
1. UserControlClass objOfUserControl = (UserControlClass)Page.FindControl("UserControlID");
TextBox txtLocation= objOfUserControl.FindControl("txtLocation");
txtLocation.Enabled = false;
2.You Can Also use Public Property as Follow
In User Control Codebehind
public bool TextBoxUSC
{
set{txtLocation.Enabled = value;}
}
In Aspx Code Behind
UserControlClass.TextBoxUSC=false;
If You are using Master Page
ContentPlaceHolder cph = (ContentPlaceHolder)this.Page.Master.FindControl("MainContent");//"MainContent" is ContentPlaceHolder's ID
UserControlClass userCntrl = (UserControlClass)cph.FindControl("UserControlID");
userCntrl.TextBoxUSC = false;

Try this
Edited
Make Enabled false in aspx you can make like this:
Add property to your UC:
public bool EnabledTextBox
{
get{return IdTextBox.Enabled;}
set{IdTextBox.Enabled=value;}
}
then in aspx:
IdOfYourUserControlWithProperty.EnabledTextBox = false;
Hope it helps

Robin You can delete
TextBox txtLocation = (TextBox)PI_CompLocationTree.FindControl("txtLocation");
txtLocation.Enabled = false;
In your aspx, add forms with runat="server"
Delete also
PI_CompLocationTree PI_CompLocationTree = new PI_CompLocationTree();
You don't need because you use FindControl
Your work is good

PI_CompLocationTree1.EnabledTextBox = false; //from .aspx page. There's no need to use FindControl if you've added it statically to the webpage.

Related

Appending to div with specific class

How can I append some html to a div with a specific class name?
frontend:
<div class="school-team-popup"></div>
backend:
StringBuilder _html = new StringBuilder();
_html.AppendFormat("<li>Hi there</li>");
I would like to append _html inside the school-team-popup div. How can I do this from the backend?
I'm going to explain the Web Forms way of doing things.
If you have some static markup that you want to selectively show/hide on your page, that's generally accomplished by setting the Visible property of the control.
<%-- This is in your ASPX markup (.aspx) --%>
<asp:Panel runat="server" id="HelloWorldPanel">
<p>Hello, world!</p>
</asp:Panel>
//This is in your code behind (.aspx.cs)
//hide the panel
HelloWorldPanel.Visible = false;
//show the panel
HelloWorldPanel.Visible = true;
If you're trying to grab dynamic data from some other source and display it on the page, you would declare the markup on your page to show this data, and then bind the data to the markup. There are many controls you can bind data to.
One example of a control you can bind data to is a repeater. Repeaters are good when you want tight control over the markup that gets rendered on the page. You bind them to some enumerable object such as a List<T> and then it will repeat some markup for each element in the enumerable object.
//This is in your project somewhere
namespace MyNamespace
{
public class Product
{
public int Id { get; set; }
public int Name { get; set; }
}
}
<%-- This is in your ASPX markup (.aspx) --%>
<ul>
<asp:Repeater runat="server" id="ProductRepeater" ItemType="MyNamespace.Product">
<ItemTemplate>
<li><%#: Item.Id %> - <%#: Item.Name %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
//this is in your code behind (.aspx.cs)
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
List<Product> products = MyDataLayer.GetProducts();
ProductRepeater.DataSource = products;
ProductRepeater.DataBind();
}
}

how to close radwindow in asp.net?

I am a using ASP.NET controller to display user detail. When RadWindow is open & I tried to close with Close button. But the problem is that after page load and post back it opens again and again. I've multi-option on page: new, save, print etc. search.
<telerik:RadWindow ID="rwReport" runat="server" Behaviors="Close" KeepInScreenBounds="true"
AutoSize="true" VisibleOnPageLoad="false" Modal="true" Title="Report ACMI Advance Payment"
DestroyOnClose="true">
<ContentTemplate>
<ucRPV:ReportViewer id="ucReportViewer" runat="server" />
</ContentTemplate>
</telerik:RadWindow>
cs file code
private void Print()
{
try
{
// this.sADPs.DisplayReport();
Hashtable reportParameters = new Hashtable();
reportParameters.Add("DataSourceName", "dsACMIAdvancePayment");
reportParameters.Add("reportName", "rptACMIAdvancePayment.rdlc");
reportParameters.Add("Id", this.hfId.Value.ToString().ConvertTo<long>());
this.ucReportViewer.clearReport();
this.ucReportViewer.showReport(reportParameters);
this.rwReport.VisibleOnPageLoad = true;
//showReport(reportParameters);
}
catch(Exception e)
{
throw e;
}
}
ASPX code:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxControlToolkit" %>
<%# Register Src="../Reports/rpvReportViewerPopup.ascx" TagName="ReportViewer" TagPrefix="ucRPV" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%# Register Src="../Common/UserControls/ToolBarActions.ascx" TagName="ToolBarActions" TagPrefix="ucTBA" %>
</td>
Do not use the VisibleOnPageLoad property to show a RadWindow, register a script that will call its show() method. Thus, subsequent postbacks will not cause it to show up by itself: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-opening-from-server.html.
Of course, preventing the form from re-submitting as Felice suggested is another thing that may also be needed.
To translate this into code:
instead of:
this.rwReport.VisibleOnPageLoad = true;
use:
string script = "function f(){$find(\"" + rwReport.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
You can try below code : this might help-
<telerik:RadScriptBlock runat="server" ID="scriptBlock">
<script type="text/javascript">
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseWin() {
//Get the RadWindow
var oWindow = GetRadWindow();
//Call its Close() method
if (oWindow) {
oWindow.Close();
}
return false;
}
</script>
</telerik:RadScriptBlock>
And on Page: yourpage.aspx;... call the function onClientClick of button:
<asp:Button ID="btnClose" Text="Close" runat="server" CssClass="button" Enabled="true" OnClientClick="CloseWin();" />
I have experienced the same problem when you reload the page because the browser resend the information and the radwindow opens again. To avoid such behavior I have adopted the following solution:
Add a hidden filed to hold the client code:
<asp:HiddenField runat="server" ID="_repostcheckcode" />
Add the following code in the code page:
protected void Page_Load(object sender, EventArgs e)
{
CancelUnexpectedRePost();
}
private void CancelUnexpectedRePost()
{
string clientCode = _repostcheckcode.Value;
//Get Server Code from session (Or Empty if null)
string serverCode = Session["_repostcheckcode"] as string ?? "";
if (!IsPostBack || clientCode.Equals(serverCode))
{
//Codes are equals - The action was initiated by the user
//Save new code (Can use simple counter instead Guid)
string code = Guid.NewGuid().ToString();
_repostcheckcode.Value = code;
Session["_repostcheckcode"] = code;
}
else
{
//Unexpected action - caused by F5 (Refresh) button
Response.Redirect(Request.Url.AbsoluteUri);
}
}
The original article can be found here.
Add a Button with an OnClick handler with the following code:
protected void CloseRadWindow(object sender, EventArgs e)
{
rwReport.VisibleOnPageLoad = false;
}

Don't know how to use custom controls in code behind

I made a simple control with 1 text box.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="sTextBox.ascx.cs" Inherits="TestingASPNET.Controls.sTextBox" className="sTextBox"%>
<asp:Textbox runat="server" ID="tbNothing"/>
<br />
I call this control as a reference in my default.aspx Here's the simple code.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="TestingASPNET._default" %>
<%# Reference Control="~/Controls/sTextBox.ascx"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" id="PlaceHolder1" />
</div>
</form>
</body>
</html>
In my code behind in default.aspx.cs I have.
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(LoadControl("~/Controls/sTextBox.ascx"));
PlaceHolder1.Controls.Add(LoadControl("~/Controls/sTextBox.ascx"));
}
This adds the 2 sTextBox onto my page.
The problem I'm having is how to I use the control like I would a normal textBox. For example.
TextBox tb = new TextBox();
tb.Text = "textbox";
PlaceHolder1.Controls.Add(tb);
This adds a text box on the page with the text "textbox" in it.
Can Someone give me a way to do EXACTLY this, but with the control sTextBox.
you can get that behavior by adding properties to your custom control.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var ctrl = (sTextBox) Page.LoadControl("~/sTextBox.ascx");
ctrl.Text = "something";
placeHolder1.Controls.Add(ctrl);
}
}
User Control :-
public partial class sTextBox : System.Web.UI.UserControl
{
public string Text { get; set; }
}
I couldn't get your code to work.
I either had to
var ctrl = (ProjectName.Controls.sTextBox) Page.LoadControl("~/Controls/sTextBox.ascx");
or import the control
using ProjectName.Controls;
When I did this, it worked.
Also your get set property wasn't work either, I had to change it to.
public string Text {
get
{
return tbNothing.Text;
}
set
{
tbNothing.Text = value;
}
}
Afterwards I added 1 more textbox into the control totaling 2. I changed the ID to tb1Text and tb2Text. I then had to get 2 methods for my get sets, which was
public string tb1Text {
get
{
return tb1.Text;
}
set
{
tb1.Text = value;
}
}
public string tb2Text
{
get
{
return tb2.Text;
}
set
{
tb2.Text = value;
}
}
inside my default code behind, I had to use
sTextBox ctrl = (sTextBox)Page.LoadControl("~/Controls/sTextBox.ascx");
ctrl.tb1Text = "something";
ctrl.tb2Text = "something 2";
PlaceHolder1.Controls.Add(ctrl);
This worked, now I know how to use 2 textboxes on 1 control :) . Hopefully it's the same with other controls that I have to make :S

Not able to find the web control on code behind?

I have some controls on a page and i am not able to access the controls in code behind, it is coming in scientific intelligence. I am getting the cause of that.
here is my HTML code of web control:
<%# Control Language="c#" AutoEventWireup="false" Inherits="DNNInfo.Modules.Classifieds.Controls.CompanyClassifiedList" %>
<div id="divDetailsDownloadFile" runat="server" class="DNNInfo_ClassifiedDownloads" visible="false">
<asp:LinkButton ID="linkDownloadFile" Text="Download File" runat="server" />
</div>
i am talking about the linkbutton here.
here is code behind code:
namespace DNNInfo.Modules.Classifieds.Controls
{
public class CompanyClassifiedList : PortalModuleBase
{ override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
try
{
this.Load += new System.EventHandler(this.Page_Load);
LinkButton linkDownload_File = (LinkButton)this.FindControl("linkDownloadFile");
if (linkDownload_File != null)
{
linkDownload_File.Click += new EventHandler(this.linkDownloadFile_Click);
}
}
catch (Exception ex)
{
}
}
}
}
It always return null in "linkDownload_File". i am not able to recognize the error. what is the cause for this behavior.
any help will be appreciated.
UPDATE: i have checked by made div visible.. but still its returning null
You need to look for it recursively, because it is within DIV. As an alternate way of doing this is to use Page.FindControl this way:
http://blog.codinghorror.com/recursive-pagefindcontrol/
but perhaps more recommended way:
Better way to find control in ASP.NET
or try to remove runat="server" on DIV
did you try the below:-
LinkButton linkDownload_File = (LinkButton)divDetailsDownloadFile.FindControl("linkDownloadFile");

Accessing Master page control in ascx file

I have a master page file that contains a 2 menu's in a 2 panel controls.
I also use a control to check if user is logged in and get the type of user.
Deppending on the type I want to show / hide the panel. The control itself is not referenced in the master page but dynamically through the CMS System.
I want to use findcontrol in the user control to find the panel control in the master page. I have tried different methods but all come back with null.
The content placeholder in the master page is
asp:Content runat="server" ContentPlaceHolderID="PHMainBlock"
and the control is called
asp:Panel ID="NormalUser" runat="server"
I have tried using the code....
Panel ph = (Panel)Page.Master.FindControl("NormalUser");
ph.Visible = false;
but brings back null, any help?
thanks..
You could create a public property in you Master Page i.e
public bool ShowPanel
{
set
{
NormalUser.Visible = value;
}
}
And call it like this
if (Page.Master is NameOfMasterPage)
{
((NameOfMasterPage)Page.Master).ShowPanel = false;
}
Because the Panel control is inside a ContentPlaceHolder control, you must first get a reference to the ContentPlaceHolder and then use its FindControl method to locate the TextBox control.
ContentPlaceHolder mpContentPlaceHolder;
Panel pn;
mpContentPlaceHolder = (ContentPlaceHolder)Master.FindControl("PHMainBlock");
if(mpContentPlaceHolder != null)
{
pn = (Panel) mpContentPlaceHolder.FindControl("NormalUser");
pn.Visible = false;
}
http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx
Here's how I do something similar and it works fine:
if (Page.Master != null)
{
var tempPanel = Page.Master.FindControl("MessagePanel") as UpdatePanel;
if (tempPanel != null)
tempPanel.Visible = true;
var temp = Page.Master.FindControl("MessageForUser") as MessageToUser;
if (temp != null)
temp.PostWarningMessage(message, msgInterval);
}
However, I have "MessagePanel" and "MessageForUser" as controls right above the ContentPlaceHolder. Here's my markup:
<asp:UpdatePanel runat="server" Visible="true" ID="MessagePanel" >
<ContentTemplate>
<msg:MainMessage ID="MessageForUser" runat="server" Visible="true" />
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="cphContent" runat="server" Visible="true">
</asp:ContentPlaceHolder>
If you have your Panel inside of a tag, then you should be able to reference the panel without needing Page.Master.FindControl.
One way would be to solve this problem with javascript (jquery):
$('.NormalUser').hide();
http://api.jquery.com/hide/

Categories

Resources