Not able to find the web control on code behind? - c#

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");

Related

Button cannot access text box

My .aspx:
<asp:LoginView runat="server">
<RoleGroups>
<asp:RoleGroup Roles="admin">
<ContentTemplate>
<asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" />
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
My code-behind
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
string Mystring = String.Format("{0}", /*I want to put Textbox.text here*/ );
}
}
The problem is that I get a "Textbox" is not defined in the current context. I fiddled around a bit and found that removing the loginview restores the functionality that I want. So why does the loginview break my ability to reference across controls that are in the same view?
C# is case sensitive. Instead of the name Textbox (b is in lower case) use TextBox. Also, I recommend you change the ID of your controls to something more meaningful. Do not set the ID of a TextBox to "TextBox"
Further to your comments, you seem to have your TextBox inside a LoginView. The only way I could get access to this control is
Control container = new Control();
LoginView1.RoleGroups[0].ContentTemplate.InstantiateIn(container);
foreach (Control control in container.Controls)
{
if (control.ID == "txtName")
{
//Phew. Got your control
}
}
Note: I have set the LoginView ID to LoginView1 and TextBox ID to txtName
Try this.TextBox! that should solve the Case Sensitivity thing! also... bad variable naming... As a rule of thumb, do not name a variable exactly like the name of a class...

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;
}

Dynamic Div creation asp.net

I am trying to create Div dynamically on the press of button click.
For that i refered this link>> http://forums.asp.net/t/1349244.aspx
and made code on server side(.cs page) as follows>>
public static int i = 0;
protected void Button1_Click(object sender, EventArgs e)
{
i++;
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+i;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
This code was giving me just one div each time when i press the button., I wanted to have addition of divs.
On client side using javascript also i tried>>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />
</div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
<script type="text/javascript">
function addDiv() {
alert("Control comming in function");
var r = document.createElement('Div');
r.style.height = "20px";
r.style.width = "25px";
r.appendChild("div");
alert("Control going out of function");
}
</script>
Both of these didnt work.
What mistake am i making?
Is there any thing wrong?
Use this
public int Index
{
get
{
if(ViewState["Index"]==null)
{
ViewState["Index"]=0;
}
else
{
ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
}
return int.Parse(ViewState["Index"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+Index;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
It is giving you one div, cause you are adding one div.
Remember that asp.net needs you to create all dynamically added controls on very PostBack after that.
If you want two controls you have to add two to the PlaceHolder.
Just use one parent div with some ID(predefined lets say id="dvDynamic") and runat="server"
and then use it the dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"
Its the simplest way, as if you are using html element in ASP.net use dom controls for better generation. Dynamic creation of control will require handled, interface and many things to co-ordinate with that control. As its not predefined by system. you have to create it.
SO choose the DOM element option. that is faster and better :)
I hope this will help :)

How to disable user control from code-behind?

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.

Viewstate is null on postback

Right, I've got something very peculiar going on here...
ASP.NET 4 page with the following property:
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
During the initial Page_Load() in (!Page.IsPostBack) the QuickShopBagInstance is populated and ViewState saved.
However when you perform a postback on the page the ViewState is empty when accessed from the postback Button_OnClick() event!!!
I've checked the Request.Form and sure enough the _Viewstate value is there and is populated. I've also ran this value through a parser and it does contain the expected data, the page has ViewStateEnabled="true" and the new .NET 4 ViewStateMode="Enabled".
I've moved on to override the LoadViewState method to check to see if it is firing, it doesn't appear to be.
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
I am really lost as to what could possibly be the problem. Any ideas?
First of all I was mistaken, the code in question was not in Page_Load but in Page_Init, although I haven't read anything that says you can't assign to ViewState at Init.
So I put together a very basic test that duplicates the problems I'm having...
<form id="form1" runat="server">
<div>
<asp:ListView id="QuickshopListView" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<asp:TextBox ID="txtItem" runat="server" Text='<%# Container.DataItem %>' />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
<br />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
</div>
</form>
public partial class Quickshop : System.Web.UI.Page
{
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (QuickShopBagInstance == null)
QuickShopBagInstance = new QuickShopBag();
if (!String.IsNullOrEmpty(Request.QueryString.ToString()))
{
string[] items = Server.UrlDecode(Request.QueryString.ToString()).Split(',');
if (items.Length > 0)
{
foreach (string item in items)
{
QuickShopBagInstance.QuickShopItems.Add(item);
}
}
}
}
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
QuickshopListView.DataSource = QuickShopBagInstance.QuickShopItems;
QuickshopListView.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (QuickShopBagInstance == null)
QuickShopBagInstance = new QuickShopBag();
QuickShopBagInstance.QuickShopItems.Add("add1");
QuickShopBagInstance.QuickShopItems.Add("add2");
QuickShopBagInstance.QuickShopItems.Add("add3");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
Button DeleteButton = (Button)sender;
ListViewDataItem item = (ListViewDataItem)DeleteButton.NamingContainer;
QuickShopBagInstance.QuickShopItems.RemoveAt(item.DisplayIndex);
}
}
[Serializable]
public class QuickShopBag
{
public List<string> QuickShopItems { get; set; }
public QuickShopBag()
{
this.QuickShopItems = new List<string>();
}
}
If you request say "/quickshop.aspx?add1,add2,add3", the ListView is populated correctly with the data from the qs, however when it comes to clicking the delete button a NullReferenceException is thrown because the ViewState hasn't persisted the QuickShopBag object.
But if you click the "Add" button, which as you can see adds to the same values to the QuickShopBagInstance (and ViewState), the ListView is populated correctly and when you click the Delete button it works perfectly as the ViewState has been persisted.
Now if you change the reading the querystring bit to Page_InitComplete as opposed to Page_Init it works perfectly. So the conclusion is...
YOU CAN'T ADD TO THE VIEWSTATE BEFORE Init_Complete!!!!!!!!
How silly of me, well whoever wrote it at least!
You seem to have ruled out most of the suggestions so far so I've created a basic page with only the information you've provided above:
class
namespace SO_Questions
{
[Serializable()]
public class QuickShopBag
{
public string MyProperty { get; set; }
}
}
code behind
namespace SO_Questions
{
public partial class TestPage : System.Web.UI.Page
{
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.QuickShopBagInstance = new QuickShopBag() { MyProperty = "Test String" };
}
Message.Text = "Value is: " + this.QuickShopBagInstance.MyProperty.ToString();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
btnSubmit.Text += QuickShopBagInstance.MyProperty;
}
}
}
markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="SO_Questions.TestPage" ViewStateMode="Enabled" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server"><div>
<asp:Label ID="Message" runat="server"></asp:Label>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" />
</div></form>
</body></html>
As expected, this runs correctly; the overridden LoadViewState method is hit (and viewstate correctly contains 2 items) and the button's text is updated.
The logical explanation would be that there's something else going on somewhere else, or you've failed to provide an additional salient piece of information.
Something that has tripped me up in the past is
Setting something in the ViewState in the page
Then trying to retrieve it in a user control. Can't find it - where has it gone?
It seems as if you should have one ViewState per page but each usercontrol keeps it's own version.
Could it be something like this?
This SO link gives a better explanation that I have just done
Just a quick note. If you are setting a ViewState value on page_load, make sure you are doing it wrapped in
if (!IsPostBack)
{
ViewState["MyValue"] = MyValue // set dynamically with appropriate code
}
If you don't do this and you do a postback...but your code setting this ViewState value is not in the !IsPostBack brackets, it will reset your ViewState value to null every time you do a postback, no matter where you enable ViewState on the page.
This may seem obvious, but it is easy to miss if you have a lot of code going on.
Or I guess you could not use !IsPostBack if you want your code to run on every postback. But if you are having trouble with a value getting set to null on postback, examine the above carefully.

Categories

Resources