ASP/C#, adding text to textbox problem - c#

For some reason, I cannot get text into any textbox or label!
I'm using Master pages and the code is going in the code behind view. I have created the textbox:
<asp:Textbox ID="whatever" runat="Server">
When I want to add some text I simply add the code in the code behind view like:
whatever.Text = "myText";
I get an error that says:
"System.NullReferenceException:Object reference not set to an instance of an object"
hightlighting this line in red: whatever.Text = "myText";
I guess its because it saying it not there but how can it let me reference the textbox?
Apologies if the answer is on the site, I have searched but found nothing. :)
This is my code in Basket.asp - I've changed the textbox to a label, it's called bskItems
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<asp:Label ID="bskItems" runat="server"></asp:Label>
<div id="cart">
<asp:Button ID="btnCheckout" CssClass="BasketBtnAdd" runat="server" CommandName="checkout" Text="Checkout" />
</div>
</asp:Content>
This is my masterpage, where I'm using a loginView. ContentPlaceHolder3 is where the textbox should be. I only want it to display a count of items.
<asp:LoginView ID="loginView" runat="server">
<LoggedInTemplate>
<asp:LoginName ID="loginName" runat="server" FormatString="Hi, {0}!"/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<%
if (HttpContext.Current.User.IsInRole("Admin"))
{
%>
<asp:SiteMapDataSource ID="admin" SiteMapProvider="admin" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu" runat="server" DataSourceID="admin">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
if (HttpContext.Current.User.IsInRole("Users"))
{
%>
<asp:SiteMapDataSource ID="user" runat="server" SiteMapProvider="user" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="user">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server"></asp:ContentPlaceHolder>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus ID="loginStatus" runat="server" />
<asp:SiteMapDataSource ID="anon" runat="server" SiteMapProvider="anon" ShowStartingNode="false" />
<asp:Menu ID="Menu2" runat="server" DataSourceID="anon">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
</AnonymousTemplate>
</asp:LoginView>

In addition to the other answers, if you're setting the value in Page.OnLoad, remember that the Master page controls haven't been created yet.
Here's a complete layout of the order in which things happen: Complete Lifecycle of an ASP Page

What I usualy do is to make the control visible as a property of my MasterPage.
On the master page (AMasterPage.master):
public TextBox MyTextBox { get { return this.theTextBoxControl; } }
So then, on a child using this masterPage (APage.aspx) :
((AMasterPage)this.Master).MyTextBox.Text = "myText";

When accessing Master Page members from Code-Behind in a Content Place Holder file, I believe you need to do:
this.Master.whatever.Text = "new Text";
Check this link on ASP.NET Master Pages, from MSDN.

You need to do get a reference to the textbox on the master page, then set the text
TextBox tb = Master.Page.FindControl("whatever") as TextBox;
if(tb != null)
{
tb.Text = "myText";
}

Set the ClientIDMode on the textbox to "Static". When the page is rendered it assigns the TextBox's ID to something random. By changing the ClientIDMode to "Static", you should be able to reference the ID because the ID will stay the same and not change.
Or try adding an OnDataBinding event handler and casting the "sender" as a (TextBox). For example:
protected void TextBox_OnDataBinding(object sender, EventArgs e)
{
var txt = (TextBox)sender;
txt.Text = "Something";
}
This should talk to the control directly.

Related

Update textbox in UserControl from another UserControl

I hava a MasterPage with 2 UserControls. When something happens in UserControl1.ascx, it has to update a TextBox in UserControl2.ascx.
I tried this inside UserControl1.ascx, but no success:
UserControl userControl = (UserControl)LoadControl("UserControl2.ascx");
var txt = (TextBox) userControl.FindControl("txtTest");
txt.Text = "Hello world";
Thanks for all help :)
The LoadControl is load a new control that is not exist on page...
Lets see this example.
You have a master page that has 2 User Controls.
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<br /><br />
<uc2:WebUserControl ID="WebUserControl2" runat="server" />
<br /><br />
<asp:Button runat="server" ID="btnOk" Text="ok" OnClick="btnOk_Click" />
</div>
</form>
and on code behind this
protected void btnOk_Click(object sender, EventArgs e)
{
WebUserControl1.TextOnMe = WebUserControl2.TextOnMe;
}
Now the user controls have this on html
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
and on code behind you get and set the Text like that on code behind
public string TextOnMe
{
get
{
return txtText.Text;
}
set
{
txtText.Text = value;
}
}
One Similar Answer
ASP.NET MasterPage only control?

Is there a simple way to call a method used to change display from a parent control?

I am trying to create a page using Ajax Tabs and user controls. The .aspx page contains a reference to a default control
<%# Register src="~/Controls/DefaultControl.ascx" tagname="DefaultControl" tagprefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<uc1:DefaultControl ID="DefaultControl1" runat="server" />
<%--<uc2:CorrespondenceControl ID="CorrespondenceControl" runat="server" />--%>
</asp:Content>
And the DefaultControl.ascx is using Ajax Tabs, one of which contains a child control within an Update Panel
asp:TabPanel ID="tbpnl2" runat="server" HeaderText="Tab With GridView with select buttons" Visible="True">
<ContentTemplate>
<asp:UpdatePanel ID="updpnl2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<uc2:Control1 ID="Control1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:TabPanel>
The DefaultControl holds a method in the code behind page which is successfully called directly from other tabs (with the markup contained directly in DefaultControl.ascx) on the DefaultControl.ascx page to change the display when Select is clicked on a gridview -
public void ShowPage()
{
gv1.DataBind();
fv1.DataBind();
tbpnl1.Visible = true; //show details tab
tbpnl2.Visible = true;
tab1.ActiveTabIndex = 1; //set details tab as current tab
txt.Text = String.Empty;
updPnl1.Update();
}
I am trying to call this method from the child Control1 when Select on a gridview is selected there, but obviously none of the elements referenced are in Control1.
I have been searching for a way to be able to use the existing method and have seen a number of suggestions including Interfaces, references like ((DefaultControl)this.DefaultControl).ShowPage(); on the code behind Control1
But as I am just starting to program I have no idea how to implement any of these solutions or what the syntax should be to get them to work.
Is there a simple, even if dirty, way to use the method from a parent control in a child control contained in an Ajax tab?
Not sure if this is what you are looking for... Below example shows calling of direct UserControl and nested UserControl method's from Web page
Default.aspx
<%# Register TagPrefix="uc" TagName="WebUserControl" Src="WebUserControl.ascx" %>
<%# Register TagPrefix="uc2" TagName="WebUserControl2" Src="WebUserControl2.ascx" %>
<form runat="server" id="form1">
<uc:WebUserControl ID="control1" runat="server" />
<hr />
<h4>
At Default.aspx</h4>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Call the function" />
</form>
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
control1.CallMe();
var control2 = (WebUserControl2)control1.FindControl("control2");
control2.CallMe2();
}
WebUserControl.ascx
<%# Register TagPrefix="uc2" TagName="WebUserControl2" Src="WebUserControl2.ascx" %>
<div runat="server">
<h3>
WebUserControl</h3>
<asp:Label ID="lbl1" Text="I am ready at WebUserControl" runat="server"></asp:Label>
<div runat="server" id="toAdd" style="color: Red;">
</div>
</div>
<hr />
<uc2:WebUserControl2 ID="control2" runat="server" />
WebUserControl.ascx.cs
public void CallMe()
{
Label lbl = new Label();
lbl.Text = "I am at WebUserControl";
toAdd.Controls.Add(lbl);
}
WebUserControl2.ascx
<div runat="server">
<h3>
WebUserControl2</h3>
<asp:Label ID="lbl1" Text="I am ready at WebUserControl2" runat="server"></asp:Label>
<div runat="server" id="toAdd" style="color: Red;">
</div>
</div>
WebUserControl2.ascx.cs
public void CallMe2()
{
Label lbl = new Label();
lbl.Text = "I am at WebUserControl2";
toAdd.Controls.Add(lbl);
}
Hope it helps someone...!!

Change Css class on a Panel thats located inside a Asp:repeater

Hello and thanks for taking your time to read this.
I'm trying to change the CSS class of a panel thats located inside a Repeater when I select a RadioButton.
<div>
<asp:RadioButtonList OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true" ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server">
<asp:ListItem Selected="True">Show Gallery</asp:ListItem>
<asp:ListItem>Show List</asp:ListItem>
</asp:RadioButtonList>
</div>
<div class="RpOutterFrame" runat="server" id="RpOutterFrame">
<asp:Repeater runat="server" ID="RP">
<ItemTemplate>
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
<img runat="server" style="width: 80px;" id="ModelImg" class="ModelImg" src='<%# string.Format("~/Content/Img/ModelImg/{0}", Eval("Image")) %>' />
<br />
<%# Eval("Model") %>
</panel>
</ItemTemplate>
</asp:Repeater>
</div>
My C#:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.Items[0].Selected == true)
{
RpOutterFrame.Attributes["class"] = "RpOutterFrame";
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
}
As you can see the Panel already has the class ShowDiv and then I would like it to change the class to ShowDiv2 when I select/click the Radiobutton.
Anyone who can help me figuar what I'm doing wrong or fix the code?
A Repeater's purpose is to repeat something. So normally it contains multiple elements. Therefore the RepeaterItem is the NamingContainer which must contain unqiue ID's and where you can find your controls via FindControl(ID).
So this does not work since this is the Page which is not the NamingContainer of the Panel:
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
You have to loop all items:
foreach(RepeaterItem item in RP.Items)
{
Panel panel = (Panel)item.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
Apart from that you should use the ASP:Panel instead of Panel.
So change
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</panel>
to
<ASP:Panel CssClass="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</ASP:Panel>

Invalid postback or callback argument (HiddenField and container Visible=false)

I've not found answers that matched my circumstances, so I'm posting an answered question hoping it will help others.
I was getting the error
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument)
at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
at System.Web.UI.WebControls.HiddenField.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.WebControls.HiddenField.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I've got a Databound ListView (with a few 100s rows), with buttons on each row. The buttons bring a popup. The popup has dropdownlists and other controls doing asynchronous postbacks. I need to make sure I do asynchronous postbacks to avoid refreshing my big table.
I get the error when I click the button on one row, then change a dropdownlist inside the popup which fires a postback (selected item changed). Boom.
Here's the markup for a reduced sample, without popup and javascript at all! It still exhibits the problem. Click twice on a button in a row to get the error.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestPopupAsynchPostback.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptMgr" runat="server" ScriptMode="Debug" EnablePartialRendering="true"
EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true"/>
<asp:ObjectDataSource ID="ListDataSource" runat="server" SelectMethod="List" TypeName="TestPopupAsynchPostback.Default" />
<asp:Label runat="server" ID="PageLabel"></asp:Label>
<asp:ListView ID="EL" runat="server" DataSourceID="ListDataSource" OnItemDataBound="EntityList_OnItemDataBound">
<LayoutTemplate>
<table border="1">
<tr id="itemPlaceholder" runat="server" enableviewstate="false">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server" id="DefaultRow" enableviewstate="false">
<td>
<asp:Label ID="Lbl" runat="server" EnableViewState="false" />
</td>
<td>
<button runat="server" type="button" id="ReportingButton" enableviewstate="false" onserverclick="ReportingButton_OnClick" causesvalidation="false">click</button>
</td>
</tr>
<%-- Fix part 1: Change SpecialRow visible = true--%>
<tr runat="server" id="SpecialRow" visible="false" enableviewstate="false">
<td>
<asp:Label ID="Lbl2" runat="server" EnableViewState="false" />
<asp:HiddenField runat="server" ID="fn_hid" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</form>
</body>
</html>
Here's the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace TestPopupAsynchPostback
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
PageLabel.Text = DateTime.UtcNow.ToString() + " IsPostBack:" + IsPostBack + " IsInAsyncPostBack:" + (sm == null ? "" : sm.IsInAsyncPostBack.ToString());
}
protected override void Render(HtmlTextWriter writer)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
if (sm != null)
{
foreach (ListViewDataItem row in EL.Items)
{
HtmlButton reportingButton = row.FindControl("ReportingButton") as HtmlButton;
if (reportingButton != null)
sm.RegisterAsyncPostBackControl(reportingButton);
}
}
base.Render(writer);
}
public IList<string> List()
{
return (new string[] { "ONE", "TWO"}).ToList();
}
protected void ReportingButton_OnClick(object sender, EventArgs e)
{
//Do something useful here, for now, just a postback event
}
protected void EntityList_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
Label lbl = e.Item.FindControl("Lbl") as Label;
Label lbl2 = e.Item.FindControl("Lbl2") as Label;
lbl.Text = lbl2.Text = e.Item.DataItem.ToString();
HtmlTableRow specialRow = e.Item.FindControl("SpecialRow") as HtmlTableRow;
if (e.Item.DataItemIndex%2 == 0)
{
HiddenField fn_hid = e.Item.FindControl("fn_hid") as HiddenField;
fn_hid.Value = "test1";
specialRow.Visible = true;
}
//Fix part 2: set SpecialRow Visible = false in code behind
//else
// specialRow.Visible = false;
}
}
}
I initially thought my javascript was at fault as I am modifying things with it. However, the process of creating a sample page has helped me find the problem.
It turns out it has nothing to do with the javascript or the popup. It's to do with a HiddenField contained inside a TR HtmlControl (asp.net server side control) with Visible=false IN THE MARKUP. I then use the code behind to set Visible=true when I need to in OnItemDataBound event.
This is what is causing the error for me: It seems that because the container (the TR SpecialRow) is Visible=false, I guess something is not rendered. I then come along in OnItemDataBound, decide that this row must be shown, and set Visible=true and set the value of my HiddenField. Boom.
If I remove the markup for the hidden field and don't set its value, no crash.
So it's not just the visibility of the TR on its own, it's the HiddenField too.
My fix: don't set Visible=false in the markup, and change OnItemDataBound to set Visible=false when required.
In other words: I was defaulting to hide things in markup and use code behind to show them. I changed this around and show things by default in markup and hide them using the code behind.
I've added the fix in the markup and code above.

.ascx user control button_click is not firing Sitefinity C#

I have come across this weird problem where my button click event is not firing. I have tried almost all the possiblities but still no luck. googling for couple of hours now but still no help. Some ppl experienced exactly the same problem on different forums but no specific answer. I tried the button_click event and also tried registring an event handler, none of them work.
In my scenario I have a sitefinity5 custom module where I am showing employee information along with employee data. on employee picture click i am displaying a JQUERY dialog where i have this button. When application load, it fires the page_load of code behind file and also when i click on employee picture at first, it fires the page_load but dont fire button_click ever. Any subsequent click on picture dont even fire the Page_Load.
Anyone's help will really really be appreciated. Following is my code snippet.
<%# Control Language="C#" AutoEventWireup="true" Inherits="SitefinityWebApp.SfCtrlPresentation.OpenAccessDataProvider_a4a794260c0b4440b466f75d11146db8" Codebehind="OpenAccessDataProvider,a4a794260c0b4440b466f75d11146db8.ascx.cs" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.PublicControls.BrowseAndEdit" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.ContentUI" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.Comments" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.Fields" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<%--<%# Register TagPrefix="jq" Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI" %>--%>
<telerik:RadListView ID="dynamicContentListView" ItemPlaceholderID="ItemsContainer" runat="server" EnableEmbeddedSkins="false" EnableEmbeddedBaseStylesheet="false">
<LayoutTemplate>
<ul class="sfitemsList sfitemsListTitleDateTmb">
<asp:PlaceHolder ID="ItemsContainer" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li class="sfitem sfClearfix">
<h2 class="sfitemTitle">
<sf:DetailsViewHyperLink ID="DetailsViewHyperLink" TextDataField="Title" runat="server" />
</h2>
<sf:AssetsField ID="AssetsField1" runat="server" DataFieldName="Picture" />
<sf:SitefinityLabel ID="SitefinityLabel1" runat="server" Text='<%# Eval("Designation")%>' WrapperTagName="div" HideIfNoText="true" CssClass="sfitemShortTxt" />
<sf:SitefinityLabel ID="SitefinityLabel2" runat="server" Text='<%# Eval("CompanyName")%>' WrapperTagName="div" HideIfNoText="true" CssClass="sfitemShortTxt" />
<sf:AssetsField ID="AssetsField2" runat="server" DataFieldName="Documents"/>
</li>
</ItemTemplate>
</telerik:RadListView>
<sf:Pager id="pager" runat="server"></sf:Pager>
<sf:ResourceLinks ID="resourcesLinks" runat="server">
<sf:ResourceFile JavaScriptLibrary="JQuery" />
</sf:ResourceLinks>
<div class="dialogTest"> <br />
<br />
Please enter your email address: <input type="text" name="emailAddress" style="width: 300px;" /><br />
<br />
<asp:TextBox ID="txtBox" runat="server"></asp:TextBox> <br/>
<asp:LinkButton Runat="server" ID="btnSubmit" Text="Submit" /> <br/>
<asp:Button ID="Button1" runat="server" Text="Button" CausesValidation="False"
onclick="Button1_Click" />
<%--<button name="btnSubmit" onclick="btnSubmit_Click" >Submit</button>--%>
</div>
<script type="text/javascript">
$j = jQuery.noConflict();
$j(document).ready(function () {
$j(".sfClearfix .sfimageWrp img").click(function () {
$j(".dialogTest").addClass("open");
//return $j(this).attr("src");
});
});
</script>
//.cs file
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Sitefinity.Modules.Events;
using Telerik.Sitefinity.Events.Model;
namespace SitefinityWebApp.SfCtrlPresentation
{
public partial class OpenAccessDataProvider_a4a794260c0b4440b466f75d11146db8 : System.Web.UI.UserControl
{
//protected override void OnLoad(EventArgs e)
//{
// base.OnLoad(e);
//}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
btnSubmit.Click+= new EventHandler(btnSubmit_Click);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
}
is this for a user control on a public front end page? go into the page properties (in the Action menu under the Pages list in the admin) and make sure to check the box to enable ViewState
By default, Sitefinity disables viewstate to improve performance.
Hope this is helpful!

Categories

Resources