ASP.net c# change pannel class - c#

<%# Page Language="C#" AutoEventWireup="true" CodeBehind="admin.aspx.cs" Inherits="******._Default"
title="Administration"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="mainHead" runat="server" >
<title>Administration</title>
<link rel="Stylesheet" href="../style/admin.css" />
</head>
<body>
<div class="topMenu">
<asp:Panel id="mnu0" runat="server" class="navButton">
Admin Home
</asp:Panel>
<asp:Panel id="mnu1" runat="server" class="navButton">
User Manager
</asp:Panel>
<asp:Panel id="mnu2" runat="server" class="navButton">
Products
</asp:Panel>
</div>
<br /><br />
<div class="subMenu">
Products Categories
</div>
<br /><br />
Welcome to the Admin
</body>
</html>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected int menuID;
protected void Page_Load(object sender, EventArgs e)
{
string menuIDdata = Page.Request.QueryString["mid"];
menuID = 0;
// Check the user is allowed here
if (!Roles.IsUserInRole("Admin"))
{
Response.Redirect("../default.aspx");
}
// Get the menu ID
if (int.TryParse(menuIDdata, out menuID))
{
menuID = int.Parse(menuIDdata);
}
else
{
menuID = 0;
}
mnu0.CssClass = "navButtonO";
}
}
I'm trying to change the class of the menu depending on which one is selected, but is there an elegant way to change the class instead of a switch/if statement? For example:
mnu[menuID].CssClass = "navButtonO";
Would change the class of the menu item.

Try:
var panel = this.Page.FindControl(menuId) as Panel;
panel.CssClass = "navButtonO";

Related

How to refer to a method in the inline code from the code-behind file?

The IsPrime method should be in a separate class in the App_Code folder, but I want to understand why this doesn't work and how to make it work.
The build error is in default.cs:
"The name 'IsPrime' does not exist in the current context"
Here is the code behind, default.cs:
using System;
public partial class _Default : System.Web.UI.Page {
protected void btnGo_Click(object sender, EventArgs e) {
lblAnswer.Text = IsPrime(Convert.ToInt32(txtNumber.Text));
}
}
Here is the markup, default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<%# Import Namespace="System" %>
<%# Page Language="c#"%>
<script runat="server">
public partial class _Default : System.Web.UI.Page {
static public Boolean IsPrime(int num) {
Boolean isPrime = true;
int limit = num / 2;
for (int i = 2; i < limit; i++) {
if (num % i == 0) { isPrime = false; break; }
}
return isPrime;
}
}
</script>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
</div>
<div>
<asp:Button runat="server" ID="btnGo" OnClick="btnGo_Click" Text="Go" />
</div>
<div>
<asp:label runat="server" ID="lblAnswer" />
</div>
</form>
</body>
</html>
I changed the reference to IsPrime in Default.cs to
default_aspx.IsPrime(...)
Evidently the inline code is put in a class called default_aspx

Cant access asp labels properties using c# in aspx page

I am trying to access an asp label field properties from c# code, and it keeps giving me the error:
The name 'lblTest' does not exist in the current context.
This is happening on my login.aspx page when calling the 'ValidateEmail' method.
There are no associated .cs files, just a login.master page.
I have a business request requiring me to modify someone elses code for enhancement, and I am guessing this has something to do with the existing content structure of .
I have tried placing this in master file, outside of the structure, etc. Still no joy.
Here is the login.aspx code:
<%# Page Language="C#" MasterPageFile="~/Masters/Login.master" AutoEventWireup="true" Culture="auto" UICulture="auto" EnableEventValidation="false" %>
<%# Import Namespace="Internal.Platform.Diagnostics" %>
<%# Import Namespace="Internal.Web" %>
<%# Import Namespace="Internal.Trial" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls.ScriptResourceProvider" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Trial" Namespace="Internal.Trial" TagPrefix="InternalTrial" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolderArea">
<script type="text/javascript">
</script>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Login ID="intLogin" runat="server" DestinationPageUrl="Default.aspx"
OnPreRender="PreRender" Font-Names="Arial,Verdana,Sans-sarif" Font-Size="0.8em"
ForeColor="#000000">
<LayoutTemplate>
<div id="logoContainer">
<div class="logo"><img src="images/icons/logo.png" width="680" height="100"></div>
</div>
<div id="logonContainer">
<div>
<div class="LoginBtn1" onclick="lgnUser('pam')">Admin - Pam</div>
<div class="User1"><img src="images/icons/user1.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('lee')">Sales - Lee</div>
<div class="User2"><img src="images/icons/user2.png" width="80" height="80"></div>
</div>
<div>
<div class="LoginBtn1" onclick="lgnUser('samantha')">Support - Samantha</div>
<div class="User1"><img src="images/icons/user3.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('larry')">Marketing - Larry</div>
<div class="User2"><img src="images/icons/user4.png" width="80" height="80"></div>
</div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
OnServerValidate="ValidateEmail" ValidationGroup="ValidateGp"
ErrorMessage="This is a custom error validator" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>
<%-- These are hidden controls used for the login process --%>
<asp:TextBox ID="UserName" runat="server" style="display: none;"></asp:TextBox>
<asp:CustomValidator ID="UserNameRequired" ValidateEmptyText="True" OnServerValidate="ValidateUserName"
ClientValidationFunction="" runat="server" ControlToValidate="UserName" ErrorMessage="<%$ resources: UserNameRequired %>"
ToolTip="<%$ resources: UserNameRequired %>" ValidationGroup="intLogin" Text="<%$ resources: asterisk %>"></asp:CustomValidator>
<asp:TextBox ID="Password" runat="server" TextMode="Password" style="display: none;"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CommandName="Login" style="display: none;" ValidationGroup="intLogin" />
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</LayoutTemplate>
</asp:Login>
</asp:Content>
<script type="text/C#" runat="server">
private const string AuthError = "AuthError";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
protected new void PreRender(object sender, EventArgs e)
{
object msg = Internal.Platform.Application.ApplicationContext.Current.State[AuthError];
if (msg == null)
{
var pageId = Internal.Platform.Application.ApplicationContext.Current.State["CurrentPageID"];
var key = pageId + ":" + AuthError;
msg = Internal.Platform.Application.ApplicationContext.Current.State[key];
}
if (msg != null)
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
Literal FailureText = (Literal)intLogin.FindControl("FailureText");
FailureText.Text = msg.ToString();
}
}
private static void SetAuthError(string errorMsg)
{
if (!string.IsNullOrEmpty(errorMsg))
{
Internal.Platform.Application.ApplicationContext.Current.State[AuthError] = errorMsg;
}
else
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
var oValidator = (CustomValidator)source;
if (oValidator == null)
{
args.IsValid = false;
SetAuthError(GetLocalResourceObject("InvalidUserNameValidation").ToString());
return;
}
char cBadChar;
BusinessRuleHelper.InvalidUserNameReason reason;
if (BusinessRuleHelper.IsValidUserNameValue(args.Value, out reason, out cBadChar))
{
args.IsValid = true;
SetAuthError(null);
}
else
{
args.IsValid = false;
switch (reason)
{
case BusinessRuleHelper.InvalidUserNameReason.NullOrEmpty:
case BusinessRuleHelper.InvalidUserNameReason.WhiteSpace:
oValidator.ErrorMessage = GetLocalResourceObject("UserNameRequired").ToString();
break;
default:
oValidator.ErrorMessage = GetLocalResourceObject("intLoginResource1.FailureText").ToString();
break;
}
SetAuthError(oValidator.ErrorMessage);
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
if (Internal.Trial.TrialLogin.VerifyEmail(args.Value.ToString()))
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
args.IsValid = true;
}
}
protected void Page_Error(Object sender, EventArgs e)
{
var userName = (TextBox)intLogin.Controls[0].FindControl("UserName");
string usrnm = userName.Text;
Exception err = Server.GetLastError();
if (err is Internal.Platform.Application.ValidationException)
{
string errMsg = err.Message;
}
}
</script>
Here is the login.master code:
<%# Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Internal.Platform.TimeZones tzs = new Internal.Platform.TimeZones();
Internal.Platform.TimeZone tz = tzs.CurrentTimeZone;
if (Request.Params["tz_info"] != null)
{
string[] tzinfo = Request.Params["tz_info"].Split(',');
if (tzinfo.Length == 11)
{
tz = tzs.FindTimeZone(tzinfo[0], tzinfo[1], tzinfo[2], tzinfo[3], tzinfo[4], tzinfo[5], tzinfo[6], tzinfo[7], tzinfo[8], tzinfo[9], tzinfo[10]);
}
}
else
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Warn("TimeZone: Unable to get timezone from client, using server timezone.");
}
Internal.Platform.Application.IContextService context = Internal.Platform.Application.ApplicationContext.Current.Services.Get<Internal.Platform.Application.IContextService>(true);
context.SetContext("TimeZone", tz);
}
Page.Title = GetLocalResourceObject("LoginPageTitle").ToString();
}
</script>
<script type="text/javascript">
function internalCleanUrl(strUrl) {
if(window.location.href.indexOf("internalclient") > -1) {
strUrl = strUrl;
} else {
strUrl = "internalClient" + "/" + strUrl;
}
return strUrl;
};
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Saleslogix</title>
<link type="text/css" href="../css/internalBase.css" rel="stylesheet" />
<link type="text/css" href="../css/BDLogin.css" rel="stylesheet" />
<style type="text/css">
body {
background-color : #f1f1f1;
background-image: none;
}
</style>
<script pin="pin" type="text/javascript">
var dojoConfig = {
parseOnLoad: true,
async: true,
isDebug: false,
locale: '<%= Global.Locale %>',
paths: { 'Internal.: '../../../jscript/Internal. },
deferredOnError: function (e) {
if (dojo.config.isDebug) {
}
}
};
</script>
<script pin="pin" type="text/javascript" src="javascript:internalCleanUrl("Libraries/dojo/dojo/dojo.js">)"</script>
</head>
<body>
<script pin="pin" src="Libraries/jQuery/jquery.js" type="text/javascript"></script>
<script pin="pin" src="jscript/BDLogin.js" type="text/javascript"></script>
<script pin="pin" src="jscript/timezone.js" type="text/javascript"></script>
<script pin="pin" src="jscript/Internal.platform/gears_init.js" type="text/javascript"></script>
<form id="Form1" runat="server" method="post" >
<div class="LoginArea" id="LoginContainer">
<asp:ContentPlaceHolder ID="ContentPlaceHolderArea" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
If you have a login.designer.cs file try to regenerate it (delete and then click on project and chose 'convert to web application').
Try this:
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<!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>
<script type="text/C#" runat="server">
protected void btnTest_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:Button runat="server" ID="btnTest" OnClick="btnTest_Click" Text="test" />
</div>
</form>
</body>
</html>

Session variable lost when click sign in

In first visit, Page_Load is running and session store correctly. When I click on Sign In button, Page_Load is call again, and then call btnSignIn_Click function, but Session is empty!
public partial class LoginPage : System.Web.UI.Page
{
UserItem userItem = null;
protected void Page_Load(object sender, EventArgs e)
{
//Initialize and validate post
RequestObj post = new RequestObj(Context);
if (post.isValid)
{
Session["post"] = post;
}
}
protected void btnSignIn_Click(object sender, EventArgs e)
{
if (Session["post"] != null)
{
RequestObj post = Session["post"] as RequestObj;
userItem = Functions.LogIn(post);
}
Response.Redirect("LogIn.aspx");
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<%# Page Language="C#" AutoEventWireup="true" CodeBehind=" LoginPage.aspx.cs"
Inherits="myNameSpace.LoginPage " %>
<!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">
<meta name="viewport" content="width=320"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%; text-align:center;">
<%if (userItem == null)
{%>
Username:
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="txtPass" runat="server" TextMode="Password">
</asp:TextBox>
<br />
<asp:Button ID="btnSignIn" runat="server" Text="Sign In"
onclick="btnSignIn_Click" />
<%}else{%>
<%=userItem.LoginName%>
<br />
<%=userItem.LoginTime.ToString()%>
<br />
<asp:Button ID="btnSignOut" runat="server" Text="Sign Out"
onclick="btnSignOut_Click" />
<%}%>
</div>
</form>
</body>
</html>
Did you mean to only set session when the page renderes initially?
Try wrapping the assignment like this
if(!IsPostBack)
{
RequestObj post = new RequestObj(Context);
if (post.isValid)
{
Session["post"] = post;
}
}
This will prevent this from being reset during a postback
Otherwise I would check the value of post in a debugger

Hiding the text box when clicking the button in the asp.net website

I have a button in my asp.net web application. When i clicking the button it will hide the text box in the same webs application .
If is it possible that anyone help me its very useful
Thank you
If the button is an html button then you can use javascript to do this:
onclick of button call following js:
document.getElementById(textBoxId).style.display = "none";
or
document.getElementById(textBoxId).style.visibility = "hidden";
from code behind TextBoxId.Visible = false;
from Javascript document.getElementById('<%=TextBoxId.ClientId%>').style.dispaly="none";
You can do it with JQuery:
<script>
$("#myButton").click(function () {
$("#myTextBox").hide("slow");
});
</script>
This is what you are looking for:
HideTextBox.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="HideTextBox.aspx.cs" Inherits="HideTextFields" %>
<!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:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:Button ID="BtnHide" runat="server" onclick="Button1_Click"
Text="Hide TextBox" />
</div>
</form>
</body>
</html>
And the code behind file
HideTextBox.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class HideTextFields : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
foreach (Control c in form1.Controls)
{
if (c is TextBox)
c.Visible = false;
}
}
}

The footer CSS does not work when the page loads dynamic content at button click

.html
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<link href="dark.css" rel="stylesheet" type="text/css" id="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="CaptionLabel" runat="server"></asp:Label>
<asp:TextBox ID="NumberTextbox" runat="server">(empty)</asp:TextBox>
<asp:Button ID="SquareButton" runat="server" Text="Square" style="background-color:Blue; color:White;" />
<asp:Label ID="ResultLabel" runat="server" Text="(empty)" CssClass="reverse"></asp:Label>
<p>
<asp:Label ID="Label1" runat="server" CssClass="footer1"
Text="Label Label Label Label LabelLabelLabel Label Label Label Label Label Label Label"></asp:Label>
</p>
<asp:RadioButton ID="radioDark" runat="server" AutoPostBack="True"
Checked="True" GroupName="grpSelectStylesheet"
oncheckedchanged="SwitchStylesheets" Text="Dark" />
<br />
<asp:RadioButton ID="radioLight" runat="server" AutoPostBack="True"
GroupName="grpSelectStylesheet" oncheckedchanged="SwitchStylesheets"
Text="Light" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SwitchStylesheets(object sender, EventArgs e)
{
if (radioDark.Checked)
stylesheet.Href = "dark.css";
if (radioLight.Checked)
stylesheet.Href = "light.css";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=DateTime.Now.Second;
for (int i = 0; i < count; i++)
{//for
Label q = new Label();
q.ID = DateTime.Now.Second.ToString();
q.Text = DateTime.Now.Second.ToString();
string spacee = "<br />";
Label space = new Label();
space.Text = spacee;
form1.Controls.Add(q);
form1.Controls.Add(space);
}//for
}
}
When the button is clicked, it works as it should but the footer does not register the expansion of the page.
Your code is completely wrong. you cannot change the stylesheet like this for a control even if the autopostback is set to true.
UPDATE: Here's how you should do it:
1- Remove the .css reference from your page.
2- Add this method to your page:
private void UpdateStylesheet(string filepath)
{
HtmlLink newStyleSheet = new HtmlLink();
newStyleSheet.Href = filepath;
newStyleSheet.Attributes.Add("type", "text/css");
newStyleSheet.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(newStyleSheet);
}
3- Add this line to your page_load event:
UpdateStylesheet("dark.css");
4- Handle the SwitchStylesheets like this:
if (radioDark.Checked)
UpdateStylesheet("dark.css");
if (radioLight.Checked)
UpdateStylesheet("light.css");

Categories