Get Textbox Value from Masterpage using c# - c#

I have a search textbox situated on a masterpage like so:
<asp:TextBox ID="frmSearch" runat="server" CssClass="searchbox"></asp:TextBox>
<asp:LinkButton ID="searchGo" PostBackUrl="search.aspx" runat="server">GO</asp:LinkButton>
The code behind for the search page has the following to pick up the textbox value (snippet):
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
Page previousPage = PreviousPage;
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
searchValue.Text = tbSearch.Text;
//more code here...
}
All works great. BUT not if you enter a value whilst actually on search.aspx, which obviously isn't a previous page. How can I get round this dead end I've put myself in?

If you use the #MasterType in the page directive, then you will have a strongly-typed master page, meaning you can access exposed properties, controls, et cetera, without the need the do lookups:
<%# MasterType VirtualPath="MasterSourceType.master" %>
searchValue.Text = PreviousPage.Master.frmSearch.Text;
EDIT: In order to help stretch your imagination a little, consider an extremely simple property exposed by the master page:
public string SearchQuery
{
get { return frmSearch.Text; }
set { frmSearch.Text = value; }
}
Then, through no stroke of ingenuity whatsoever, it can be seen that we can access it like so:
searchValue.Text = PreviousPage.Master.SearchQuery;
Or,
PreviousPage.Master.SearchQuery = "a query";

Here is a solution (but I guess its old now):
{
if (PreviousPage == null)
{
TextBox tbSearch = (TextBox)Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
else
{
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
}

Related

update linkbutton text dynamically in asp.net

I am trying to change the text for the link-button dynamically based on if the user is logged in or not. The text should be Log-out if user is logged in and vice versa. It is always showing Login. I am not sure what I am doing wrong here.
<p><asp:LinkButton ID="MyLnkButton" runat="server" EnableViewState = "False" onClick="MyLnkButton_Click" Text="" ForeColor="Red"/></p>
code behind
if (!Page.IsPostBack)
{
if (Session["USRID"] != null)
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}
else
MyLnkButton.Text = "Login";
}
I would reverse the logic question is do you need to call Bind_GV regardless of post back.. if so I will depict in my code below
if (Page.IsPostBack && !string.IsNullOrEmpty((string)Session["USRID"]))
{
MyLnkButton.Text = "Login";
}
else
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}

How to I get ASP.NET Page Name

Easy one here.
I have a control inside a control inside a masterpage. The page name looks something like this in HTML
ctl00$MasterPageBody$MainControl$ChildControl
Any idea how I can get the above from code behind?
Thanks!
It's the clientID property of the control.
If we're talking about a top-level control on the page, or at least one that isn't in any sort of repeating type, you can just use the ClientID property.
<asp:Label runat="server" ID="testLabel" />
<script>
$('#<%= testLabel.ClientID %>').click(function() { ... });
</script>
If we're talking about something that isn't accessible directly like that, you'll have to do the same thing, but it'll have to be wrapped in a FindControl. The example of that isn't so clean, so I'll trust you can understand from my words. But basically, if you have a label that shows code-behind-given text on each row of a GridView, you'll have to call ((Label)e.Row.FindControl("testLabel")).ClientID. Still pretty straight-forward, but a bit more complicated than the first case.
You should use a function similar to this:
public static Control FindControlRecursive(Control ctl, string id) {
if (!ctl.HasControls())
return null;
Control res = null;
foreach(Control c in ctl.Controls) {
if (c.ID == id) {
res = c;
break;
} else {
res = FindControlRecursive(c, id);
if (res != null)
break;
}
}
return res;
}
in this way:
Control ChildControl = FindControlRecursive(this.Page, "ChildControl");
string ID = ChildControl.ClientID;

Access previous page controls value

i have a problem i want to access controls of previous pages values. I know that i can use postbackurl but i must use OnClientClick property because i must call javascript method and according to the criterias my url change. Below method is called OnClientClick property. This page name Calculator.aspx
function redirectSellPage() {
var type = getParameterByName('type');
if (type == 'test') {
window.location.href = "Change.aspx?PageType=a";
} else if (a == null || a == "") {
window.location.href = "Change.aspx?PageType=b";
} else {
window.location.href = "Change.aspx?PageType=c";
}
}
I want to access Calculator.aspx controls values in Change.aspx.
How can i do that.
In source page, which in your case is Calculator.aspx, add this:
public String Value1
{
get
{
return YourTextBoxId.Text;
}
}
On the target page, which in your case is Change.aspx, add a # PreviousPageType page directive that points to the source page.
<%# PreviousPageType VirtualPath="~/Calculator.aspx" %>
Now in target page use PreviousPage property to access values.
String val = PreviousPage.Value1;

Asp.net passing values to the User control then display them

I'm trying to make a generic Search UserControl that can be given some values, based on those values the search results will display. However I'm currently trying to display the results of my values, and they always show up as my default values.
my UserControl code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ProductSearch.ascx.cs" Inherits="..." %>
<asp:Label ID="lblSearchWord" runat="server" />
<asp:Label ID="lblSearch" runat="server" />
Code Behind:
private string _searchWord = string.Empty;
private int _search = -1;
public string SearchWord
{
get { return _searchWord; }
set { _searchWord = value; }
}
public int Search
{
get { return _search; }
set { _search = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
lblGroupId.Text = LevelId.ToString();
lblSearchWord.Text = SearchWord;
}
When I press the search button on the main aspx.cs page I do the following:
protected void btnSearch_Click(object sender, EventArgs e)
{
ucPS.SearchWord = txtProductSearch.Text;
ucPS.Search = 1
}
My aspx page contains the following
<%# Register src="UserControls/ProductSearch.ascx" tagname="ProductSearch" tagprefix="ps" %>
<ps:ProductSearch id="ucPS" runat="server" />
My problem is that I can't use Query strings as the user might have selected some other things on this page that I need to keep the state of, however I did test that one and foudn it working.
Where am I going wrong? or is there an better alternative (except for query strings).
All variables in a page are disposed at the end of the page-lifecycle. Hence SearchWord will always be initialized with the default value on every postback.
You need to persist it somewehere else, for example in a ViewState variable.
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
return "";
else
return (String)ViewState["SearchWord"];
}
set { ViewState["SearchWord"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
ViewState["SearchWord"] = string.Empty;
return ViewState["SearchWord"];
}
set
{
ViewState["SearchWord"] = value;
}
}
and I use databind not pageload, this way your usercontrol doesn't load unless you call it.
protected override DataBind()
{
//you can add a condition here if you like
if(SearchWord != string.Empty)
lblSearchWord.Text = SearchWord;
}
to call this from aspx:
usercontrol.SearchWord = "my word";
usercontrol.DataBind();
and thats it..

NullReferenceException when assigning a Session variable/value

I have in many places in my ASP.NET project used the Session variable for storing data. I usually write something like this:
public uint MyPropery
{
get
{
object o = Session["MyProperty"];
if (o != null)
return (uint)o;
else
return 0;
}
set
{
Session["MyProperty"] = value;
}
}
However, this time I get a NullReferenceException in the setter. As far as I know, it is valid to assign the Session variable in the manner above. Also, Session is not null and neither is value.
Any ideas on this?
Edit:
Adding the code for the UserControl in which the property exists. I am using ext.net but that shouldn't have anything to do with this. One thought that crossed my mind:
The UserControl (seen below) is added dynamically in code-behind of a page. Can that have anything to do with it?
I am adding UserControls like this (on a Page):
foreach(CoreCommons.System.Comment c in cg.Reply_Comments)
{
WebApplicationExtNetTest.Secure.UserControls.CoreComment cc = new UserControls.CoreComment();
cc._Comment = c; // here is where i get the NullRef
this.Panel1.ContentControls.Add(cc);
}
Markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CoreComment.ascx.cs" Inherits="WebApplicationExtNetTest.Secure.UserControls.CoreComment" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<ext:Panel runat="server" ID="CoreCommentOuterPanel" BodyStyle="background: #FFFDDE">
<Items>
<ext:ColumnLayout runat="server">
<Columns>
<ext:LayoutColumn ColumnWidth="0.8">
<ext:Image runat="server" ImageUrl="/Resources/bullet_triangle_green_16x16.png" Align="AbsMiddle"></ext:Image>
<ext:Label runat="server" ID="lblCommentInfo"></ext:Label>
</ext:LayoutColumn>
<ext:LayoutColumn ColumnWidth="0.2"><ext:Button runat="server" ID="btnDelete" Icon="Delete"></ext:Button></ext:LayoutColumn>
</Columns>
</ext:ColumnLayout>
<ext:Label runat="server" ID="lblComment"></ext:Label>
</Items>
</ext:Panel>
Code-behind:
namespace WebApplicationExtNetTest.Secure.UserControls
{
public partial class CoreComment : System.Web.UI.UserControl
{
public CoreCommons.System.Comment _Comment
{
get
{
object o = Session["CoreComment_ObjectId"];
if (o != null)
return (tWorks.Core.CoreCommons.System.Comment)o;
else
return null;
}
set
{
Session["CoreComment_ObjectId"] = value;
SetComment();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void SetComment()
{
if (_Comment == null)
{
lblCommentInfo.Text = "";
lblComment.Text = "";
}
else
{
lblCommentInfo.Text = _Comment.Author + ", " + _Comment.TimeStamp.ToString("g");
lblComment.Text = _Comment.Text;
}
}
}
}
I'm almost completely sure the NullReferenceException is thrown in SetComment() because none of the CoreComment's child controls (lblComment, lblCommentInfo) are properly instantiated at the point you set the _Comment property.
The reason these child controls are not instantiated is indeed the way you currently add the CoreComment controls. For dynamically adding UserControls, you must use Page.LoadControl() (see: here) to create a new instance of the control, as it does some behind-the-scenes magic to ensure it is properly initialized, which includes the instantiation of the child controls.
On a sidenote, personally I'd change SetComment() to SetComment(CoreCommons.System.Comment comment) and use the parameter instead of repeatedly calling the getter, or, if staying with the original, at least call the getter only once and store the result in a local variable. With what I assume is probably InProc session storage it won't make much of a difference, but in any other storage mode you'd repeatedly deserialize the Comment object for no reason.
You need to use the Page.LoadControl() method instead , please look here
BTW:the problem is in adding the control programatically with that way.
Use:
return Session["MyProperty"] as uint? ?? 0;
and post somewhere full exception stack trace with inner exception(s)

Categories