I am using asp.net C#, I have some problems. I want to change text label in site master when click on button.
In site.master:
<asp:label runat="server" id="lblUser">
Other forms, I have tried with this code, but not working:
((Label)Master.FindControl("lblUser")).Text = "Hello USER";
This may work:
Master.Controls.OfType<System.Web.UI.WebControls.Label>.First(c => c.ID == "lblUser").InnerText = "Hello USER";
What you done is correct that must work.
you can achieve that like
In Site.Master.cs make label control public
public string GetUser
{
get
{
return lblUser.Text;
}
set
{
lblUser.Text = value;
}
}
Then set the value to GetUser in otherform.aspx.cs
if(!Ispostback)
{
Master.GetUser = "Hello USER";
}
Related
I have a project in VS 2013 with master page. In the Root.master I have the "Log In" which redirects me to the login page.
Log In
When I login I'm redirected to a certain page, let's say it Default.aspx.
In Default.aspx.cs I have:
if (Session["username"] == null)
{
Response.Redirect("Logare.aspx");
}
else
{
loginLink.Text ="Welcome, "+ Session["username"];
}
How could I do so when I'm logged in the text from Root.master to change from "Log In" to "Welcome, username"? I tried to get the loginLink id from Root.master but it's not known in Default.aspx.cs.
UPDATE
This is how "Log In" from Root.master is now:
<asp:Label ID="Label8" runat="server" Text="Log In"></asp:Label>
In Default.aspx.cs I have now:
if (Session["username"] == null)
{
Response.Redirect("Logare.aspx");
}
else
{
Label mpLabel = new Label();
mpLabel = (Label)Master.FindControl("Label8"); mpLabel.Text = "Welcome, " + Session["username"];
}
But, with this, I'm getting an error
Object reference not set to an instance of an object.
at mpLabel.Text = "Welcome, " + Session["username"];
So if I understood your question correctly, this is just about accessing control declared on the master page from within the content page code behind. You have two options to achieve that.
FindControl
Code is simple (borrowed from OP's own comment):
Label mpLabel = (Label) Master.FindControl("loginLink");
However be aware that FindControl works only with immediate children of the control. So if your structure looks like
MasterPage
Control1
Control2
loginLink
You will need to something like this:
Control c1 = Master.FindControl("Control1");
Control c2 = c1.FindControl("Control2");
Label mpLabel = (Label) c2.FindControl("loginLink");
Alternatively you can use recursive version of FindControl . It is not available out of the box, but many (really many) versions are on the web already. Here is one.
Expose controls via Master's interface
In your master page code behind define a property like that:
public Label LoginLabel
{
get { return this.loginLabel; }
}
And on the content page just use it. Don't forget to cast master to your specific type:
Label loginLabel = ((YourMasterPageClass)Master).LoginLabel;
That might not be particularly safe, so you can expose just label text instead:
public Label LoginLabelText
{
get { return this.loginLabel.Text; }
set { this.loginLabel.Text = value; }
}
((YourMasterPageClass)Master).LoginLabelText = "Welcome!";
I have a Textbox added to an .ascx control page as follows:
<asp:TextBox id="txtDescription" runat="server" Width="500" TextMode="MultiLine" Rows="2"></asp:TextBox>
And it would show something like this when first loaded (4 spaces at the start included):
Description goes here
Put simply, it's a Multiline Textbox with 2 lines. However, whenever we do a Postback to the server, when the page reloads, we get this:
Description goes here
Another Postback.
Description goes here
And so on. Basically, every time the page is refreshed after a Postback, it adds 4 spaces to the start of the textbox. On some pages, this isn't an issue, however, if the user is entering a fair bit of data into a Gridview or some other Control, the contents of the Textbox can end up shunted 20 or so characters to the right, sometimes out of the bounds of the Textbox.
Put simply, this is an issue for our company, as it is occurring across all of our pages. One of our clients has several times made a pass "...and could you do something about the spaces at the beginning of the textboxes at some point?"
Now, a temporary fix we have employed is the following code in our PageLoad function, however, we are still left with 4 spaces at the beginning of the Textbox. And rolling it out across 100's of .ascx and .aspx controls/pages isn't really a solution.
if (IsPostBack)
txtDescription.Text = txtDescription.Text;
Now the big question is, does anyone know how to remove these mysterious 4 spaces that keep getting added to the start of a Multiline Textbox?
A typical html textarea (multiline textbox) looks like this:
<textarea>This is some content</textarea>
Now if your output looks like:
<textarea>
This is some content
</textarea>
Then you will introduce your space issue.
When you save this content you gain the 4 spaces at the beginning (the indentation). Now you load those 4 spaces back and suddenly you have 8 spaces: 4 from the markup and 4 from the saved content. This pattern continues each time you save the content.
I am unfamiliar with how you (ASP Web Forms) are generating your content, but this should give you a point of investigation.
I encounter this problem too. May be mono asp.net bug.
This is my found way,
build a custom server control to replace multiline textbox.
It's work with asp.net integrated validation framework.
Somebody have better idea?
[ValidationProperty("Text")]
[ControlValueProperty("Text")]
[DefaultProperty("Text")]
public class TextArea: WebControl, IPostBackDataHandler, IEditableTextControl
{
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Textarea; }
}
public bool CausesValidation
{
get
{
if (ViewState["CausesValidation"] == null)
return false;
return (bool)ViewState["CausesValidation"];
}
set
{
ViewState["CausesValidation"] = value;
}
}
public string ValidationGroup
{
get
{
return (string)ViewState["ValidationGroup"] ?? "";
}
set
{
ViewState["ValidationGroup"] = value;
}
}
public string Text
{
get
{
return (string)ViewState["Text"] ?? "";
}
set
{
ViewState["Text"] = value;
}
}
public bool ReadOnly
{
get
{
if (ViewState["Readonly"] == null)
return false;
return (bool)ViewState["Readonly"];
}
set
{
ViewState["Readonly"] = value;
}
}
public int Rows
{
get
{
if (ViewState["Rows"] == null)
return 0;
return (int)ViewState["Rows"];
}
set
{
ViewState["Rows"] = value;
}
}
public int Columns
{
get
{
if (ViewState["Columns"] == null)
return 0;
return (int)ViewState["Columns"];
}
set
{
ViewState["Columns"] = value;
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
if (Enabled && !IsEnabled)
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
if (ReadOnly)
writer.AddAttribute(HtmlTextWriterAttribute.ReadOnly, "readonly");
if (Rows != 0)
writer.AddAttribute(HtmlTextWriterAttribute.Rows, Rows.ToString(NumberFormatInfo.InvariantInfo));
if (Columns != 0)
writer.AddAttribute(HtmlTextWriterAttribute.Cols, Columns.ToString(NumberFormatInfo.InvariantInfo));
base.AddAttributesToRender(writer);
}
public override void RenderControl(HtmlTextWriter writer)
{
RenderBeginTag(writer);
writer.WriteEncodedText(Text);
RenderEndTag(writer);
}
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
var strPostBack = postCollection[postDataKey];
if (ReadOnly || Text.Equals(strPostBack, StringComparison.Ordinal))
return false;
Text = strPostBack;
return true;
}
public void RaisePostDataChangedEvent()
{
if (!Page.IsPostBackEventControlRegistered)
{
Page.AutoPostBackControl = this;
if (CausesValidation)
Page.Validate(ValidationGroup);
}
TextChanged(this, EventArgs.Empty);
}
public event EventHandler TextChanged = delegate { };
}
I also had same issue. To remove extra spaces use textbox_TextChanged event and bind it to textbox.
protected void txtDescription_TextChanged(object sender, EventArgs e)
{
String strReplace = Regex.Replace(txtDescription.Text.Trim(),#"\t|\n|\r","");
txtDescription.Text = strReplace;
}
Bind TextChanged event to textbox:
<asp:TextBox id="txtDescription" runat="server" Width="500" TextMode="MultiLine" Rows="2" OnTextChanged="txtDescription_TextChanged"></asp:TextBox>
Note: It won't remove the first space, but will work with subsequent spaces of postback.
Your only option is to breakpoint the code and see where they are appearing from.
I know this question is asked before for assigning text to textbox, but they didn't have answers or the given answers didn't work for me. I have a static function for translations and I'm trying to use that to assign a placeholder to a Textbox. How can I do it in aspx page?
My code is:
<asp:TextBox ID="search" runat="server"
placeholder='<%# islem.DilGetir(7) %>'>
</asp:TextBox>
This one returns this sourcecode:
<input name="ctl00$search" type="text" id="ctl00_search">
You should set this attribute from the page code behind:
search.Attributes["placeholder"] = islem.DilGetir(7)
you can use ajax controll toolkit text box watermark I find it to be mnost usefull in aspx apps
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID ="search" WatermarkText="textthe my name" WatermarkCssClass="watermarked">
</asp:TextBoxWatermarkExtender>
on the back end
TextBoxWatermarkExtender1.WatermarkTex=islem.DilGetir(7);
I experienced the same problem. The exact solution: Take all placeholder's text to hiddenfield component(separated with , ) and with JS, take the inside array hiddenfield text and assign to input text's placeholder attr with jQuery or JS.
this code for multiselectbox choosen js and normal selectbox.
public void SelectFill(DataTable dtResult, HtmlSelect htmlSelect, string placeHolder, string textColumn, string valueColumn, string value)
{
htmlSelect.DataSource = dtResult;
htmlSelect.DataTextField = textColumn;
htmlSelect.DataValueField = valueColumn;
htmlSelect.DataBind();
bool isMultiple = false;
foreach (var item in htmlSelect.Attributes.Keys)
{
if (item.ToString() == "multiple")
{
isMultiple = true;
}
}
if (isMultiple)
{
htmlSelect.Attributes["data-placeholder"] = placeHolder;
}
else
{
ListItem placeHolderItem = new ListItem(placeHolder, "-1");//create placeholder option for non multible selectbox
placeHolderItem.Attributes.Add("disabled", "disabled");
htmlSelect.Items.Insert(0, placeHolderItem);
htmlSelect.Items[0].Selected = true;
}
}
What I want to achieve is once a user have entered wrong data, an image label will be displayed.
Visible method is not recommended due to my lblMessage serve for other purposes as well.
My big big problem now is once users corrected their input field, the label message is disabled but the image still visible, just because i set my lblMessage to null.
Is there any method I can use like when there are something is lblMessage invoke image CSS but whenever there is nothing in lblMessage, no css is invoked?
if (!Utils.mtdIsBlank(Session["Message"]))
{
lblMessage.Text = Session["Message"].ToString();
Session["Message"] = null;
}
else
{
lblMessage.Text = "";
}
Seems like your problem is that you don't know how to add/remove styles to your asp.net controls: You can use CssClass for asp.net controls (label, panel,...) like this:
lbl.CssClass = "new-class";
For your example, something like this should work for you:
if (!Utils.mtdIsBlank(Session["Message"]))
{
//If is not blank no image
lblMessage.Text = Session["Message"].ToString();
Session["Message"] = null;
lblMessage.CssClass = "no-img";
}
else
{
//Show alert image
lblMessage.Text = "";
//Replace with-img with the css class you are using
lblMessage.CssClass = "with-img";
}
Then you need to add a css property:
.no-img{
background: none;
//Anything else
}
I am using shopping cart icon showing number of products in cart. but when i add item to cart shopping is not updated.so i want to know if there is any method to change master page label's text after a button click on child page.
I would recommend to provide a public property in your MasterPage that you can use to set/get the Label's Text.
in your Master(assuming it's type is called SiteMaster):
public String ShoppingCartNumber{
get{ return LblShoppingCart.Text; }
set{ LblShoppingCart.Text = value; }
}
In your button's click event handler:
SiteMaster master = (SiteMaster)Page.Master;
master.ShoppingCartNumber = "1234";
This approach is straight-forward, less prone to errors and easily readable. You could even change the control in your master without needing to change the pages (f.e. if you want to replace the Label with a TextBox).
Try this
Label mpLabel = (Label) Master.FindControl("masterPageLabel");
if(mpLabel != null)
{
Label1.Text = "Master page label = " + mpLabel.Text;
}
Try this:
Add in your masterpage.cs file:
public Label lbl
{
get { return YourLabelId; }
set { YourLabelId= value; }
}
Add this in your content page:
<%# MasterType VirtualPath="~/YourMasterPageName.Master" %>
Then access in content page in your button click event:
string name = Master.lbl.text;